Display entity restrictions in a message form in Symfony 2

I have an object that has these fields.

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; ..... } 

Now I would like to derive these restrictions in a form similar to this.

 <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"> 

In any case, I can achieve this in Symfony 2 without manually creating these messages and data attributes in the form again.

+8
forms symfony
source share
1 answer

You can achieve this using the following code snippet.

Here I insert a validator service to read class metadata (annotations). In our case, the User class. The prepareConstraints function then prepareConstraints through each property constraint and adds them to an array whose key is the name of the property. Then in buildForm add functions as attr field values.

On your constructor

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

In your UserType class :

 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'], ) ) ... } 

}

Result

 <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=""> 
+1
source share

All Articles