Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output an entity constraints in form with message in Symfony 2

Tags:

forms

symfony

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.

like image 810
nicholasnet Avatar asked Nov 03 '15 17:11

nicholasnet


1 Answers

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="">
like image 142
Turdaliev Nursultan Avatar answered Sep 28 '22 03:09

Turdaliev Nursultan