Question

A form I had built has a single exception. To "save costs", an existing property of the Model would be used for this "new field".

My target:

  • Change the label of the existing property
  • Change the validation of the existing property
  • Change the error message of the existing property

I worked out how to add validations and change the label, but I can't seem to find where to set the error message of the existing field.

// MyFormType.php
<?php
if (!empty($options['unique']) && $options['unique'] == 'some_variable') {
    $event->getForm()->add($factory->createNamed('existing_field', 'number', null, array(
        'label'      => 'Number field',
        'required'   => true,
        'max_length' => 6,
        'constraints' => array(
            new MinLength(6),
            new MaxLength(6),
        ),
    )));
} else {
    $event->getForm()->add($factory->createNamed('existing_field', 'text', null, array(
        'label' => 'Text field',
    )));
}

Is there a key for the field options that will allow me to set a validation error message?

Was it helpful?

Solution

MinLength and MaxLength have been combined into just Length in 2.3 and I don't have as copy of 2.1 or 2.2 up and running, but I checked the old 2.1 and 2.2 API and this should work for you.

// MyFormType.php
<?php
if (!empty($options['unique']) && $options['unique'] == 'some_variable') {
    $event->getForm()->add($factory->createNamed('existing_field', 'number', null, array(
        'label'       => 'Number field',
        'required'    => true,
        'max_length'  => 6,
        'constraints' => array(
            new MinLength(array(
                'limit'   => 6,
                'message' => 'This field must be atleast 6 characters long'
            )),
            new MaxLength(array(
                    'limit'   => 6,
                    'message' => 'This field must be shorter than 6 characters'
                )),
        ),
    )));
} else {
    $event->getForm()->add($factory->createNamed('existing_field', 'text', null, array(
        'label' => 'Text field',
    )));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top