在Symfony 2中输出带有消息的实体约束

时间:2015-11-03 17:17:51

标签: forms symfony

我有一个拥有这些字段的实体。

class User implements UserInterface, \Serializable
{
  /**
   * @var string
   *
   * @ORM\Column(name="first_name", type="string", length=64)
   * @Assert\NotBlank(message="First name cannot be blank")
   * @Assert\Length(max=64, maxMessage="First name cannot more than {{ limit }} characters long")
   */ 
   private $firstName;

   .....

}

现在我想以这样的形式输出这些约束。

<input type="text" required="required" data-required-msg="First name cannot be blank" name="firstname" data-max-length="64" data-max-length-msg="First name cannot be more than 64 characters long">

无论如何,我可以在Symfony 2中实现这一点,而无需再次在表单中手动创建这些消息和数据属性。

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码段来实现此目的。

这里我注入一个验证器服务来读取类的元数据(注释)。在我们的案例中User。然后在prepareConstraints函数上迭代每个属性约束并将它们添加到key是属性名称的数组中。然后在buildForm函数上添加约束作为字段attr值。

在你的委托人上

$user = new User();
$form = $this->createForm(new UserType($this->get('validator'),$this->get('translator')), $user);

在您的 UserType班级上:

class UserType extends AbstractType
{
    private $metaData;
    private $constraintMessages;
    private $translator;

public function __construct(ValidatorInterface $validatorInterface,TranslatorInterface $translator)
{
    $this->metaData = $validatorInterface->getMetadataFor('AppBundle\Entity\User');
    $this->translator = $translator;
    $this->prepareConstraints();
}

private function prepareConstraints()
{

    foreach ($this->metaData->properties as $property) {
        foreach ($property->constraints as $constraint) {
            $class = get_class($constraint);
            $constraintName = substr($class, strrpos($class, '\\') + 1, strlen($class));
$message = property_exists($class, 'message') ? $constraint->message : $constraint->maxMessage;;
            $this->constraintMessages[$property->name]['data-'.$constraintName] = $this->translator->trans($message,array('{{limit}}'=>...))
        }
    }
}

/**
 * {@inheritdoc}
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add(
            'name',
            null,
            array(
                'label' => 'label.name',
                'attr'  => $this->constraintMessages['name'],
            )
        )
        ...
}

}

<强>结果

<input type="text" id="app_user_name" name="app_user[name]" required="required" data-notblank="This value should not be blank." class="form-control" value="">