1
votes

Present fact :

  • I have a User entity;
  • I have a FormType class for the User entity;
  • I have a twig template to render the FormType class;
  • I have a fully functional creation of a new user;

Issue :

  • I would like to create a new template for editing exist users;
  • I wouldn't like create a new form type just for editing;
  • I would like to edit User with FormType, which is already used for creating new users;
  • I always use a same entity User (create, edit, etc...);

For different render of this FormType, I would like to change the behaviour of validation system. For example:

  • Creating: Password fields is mandatory
  • Editing: Password is not mandatory (if blank then password doesn't change, but if not blank change in database)

When I read in web, all the solution based from unique constraints for one entity. Never apply different rule constraints for the same field entity. Indeed I don't understand how can use a same FormType for different action CRUD

The question is : How can apply different constraints rules for the same fields entity dealing with differents logical utility.

Schema Entity Form constraints

1

1 Answers

3
votes

Use validation groups:

class User
{
    /** @NotBlank(groups={"registration"}) */
    private $password;

    // ...
}
// registration
$form = $this->createForm(UserType::class, $userModel, [
    'validation_groups' => ['registration', 'Default']
]);

// edit
$form = $this->createForm(UserType::Class, $userModel);