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="">
Turdaliev nursultan
source share