È possibile ottenere ciò utilizzando il seguente snippet di codice.
Qui sto iniettando un servizio di convalida per leggere i metadati (annotazione) di una classe. Nel nostro caso la classe User
. Quindi, sulla funzione prepareConstraints
, iterando su ogni vincolo di proprietà e aggiungendoli a un array il cui valore è key
. Quindi su buildForm
, la funzione aggiunge vincoli come valori di campo attr
.
Sul constroller
$user = new User();
$form = $this->createForm(new UserType($this->get('validator'),$this->get('translator')), $user);
SulUserType
classe:
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'],
)
)
...
}
}
Risultato
<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="">
fonte
2015-11-10 15:16:32
Sembra che tu voglia fare qualcosa del genere: http://stackoverflow.com/questions/15573935/symfony2-get-all-validation-constraints-on-an-entity-yml-xml-annotations –