Skip to content

[Form] Document "class constraints" for data class-less forms #18969

Closed
@PrOF-kk

Description

@PrOF-kk

Symfony supports using a Form without using a Data Class.
In that page it mentions how to validate individual fields using a constraint, however it's also possible to add constraints to the root form:

  • In the controller ->
$form = $this
    ->createFormBuilder(null, [
        'constraints' => [
            new Expression([
                'expression' => 'value["firstName"] == "john"',
            ])
        ]
    ])
    ->add('firstName')
    ->add('lastName')
    ->getForm();

(src)

  • In the FormType using configureOptions ->
public function configureOptions(OptionsResolver $resolver)
{
    $collectionConstraint = new Collection(array(
        'CardNumber' => array(
            new Assert\CardScheme(array(
                'schemes' => array('VISA', 'MASTERCARD', 'DISCOVER'),
                'message' => 'The credit card number you entered is invalid.'))
        ),
        'SecurityCode' => array(
            new Length(array('min' => 3, 'max' => 3))
        )
    ));

    $resolver->setDefaults(array(
        'data_class' => null,
        'constraints' => $collectionConstraint
    ));
}

(src)

(Note: Callback constraints are also allowed and have access to the whole form)

Metadata

Metadata

Assignees

No one assigned

    Labels

    FormhasPRA Pull Request has already been submitted for this issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions