I have an entity which have 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 output these constraints in form somewhat like 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">
Is there anyway I can achieve this in Symfony 2 without manually creating these messages and data attributes in form again.
You can achieve this using following code snippet.
Here I am injecting a validator service to read a metadata(annotation) of a class. In our case User
class. Then on prepareConstraints
function iterating through each property constraints and adding them to an array whose key
is property name. Then on buildForm
function adding constraints as a field attr
values.
On your constroller
$user = new User();
$form = $this->createForm(new UserType($this->get('validator'),$this->get('translator')), $user);
On 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="">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With