2
votes

I am trying to create a form in Symfony2 with a text input field that accepts a string consisting of 6 digits followed by a dash followed by four digits (e.g. 123456-7890). It does work, but I'm getting inconsistent HTML markup depending on exactly how I add the field to the form.

This is from the entity:

class Kursist
{
...
/**
 * @ORM\Column(type="string", length=11)
 */
protected $cpr;
....
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
    $metadata->addPropertyConstraint('cpr', new NotBlank());
    $metadata->addPropertyConstraint('cpr', new Regex(array(
        'pattern' => '/^\d{6}-\d{4}$/',
    )));
}

From the form definition:

class KursistType extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder->add('cpr');
    ...
  }
}

From the twig template:

<form action= ... >;
  {{ form_row(form.cpr) }}
    ...
</form>

This is what the browser source code looks like - note the pattern and maxlength attributes:

<label for="KursistType_cpr" class="required">Cpr</label><input type="text" id="KursistType_cpr" name="KursistType[cpr]" required="required" maxlength="11" pattern="\d{6}-\d{4}" value="123456-7890" />

I want to use my own label rather than the default, so I change the form field defition:

    class KursistType extends AbstractType
    {
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
        $builder->add('cpr','text', array('label' => 'CPR'));
        ...

But now when I look at the browser source code, the pattern and maxlength attributes have gone:

    <label for="KursistType_cpr" class="required">CPR</label><input type="text" id="KursistType_cpr" name="KursistType[cpr]" required="required" value="123456-7890" />

Is there some way to modify the label using the FormBuilderInterface without these attributes being dropped?

1
I looks like a Symfony2 bug, it should work normally...Wouter J

1 Answers

3
votes

This inconsistency is due to type options guessing which happens in first case when you dont provide any additional information about field to form builder.

When option guessing is disabled, you can provide field attributes explicitly.

$builder->add('cpr','text', array('label' => 'CPR', 'pattern' => '\d{6}-\d{4}'));

Or even you can keep option guessing enabled, but override only label attribute

$builder->add('cpr',null, array('label' => 'CPR'));