Search code examples
symfonysymfony-formssymfony4

Symfony 4.* Setting field values in controller and prevent validatinon error: This value should not be null


I am using Symfony 4.2.3. I have an entity called Article which has amongst others the following fields:

  • version
  • versionUserId
  • versionTimestamp

which have * @Assert\NotNull validation mark.

I want to set value of those fields manually in the controller e.g. using:

$article->setVersionUserId($user);
                $article->setVersionTimestamp(new \DateTime());
                $article->setVersion(1);

However, as I understand $form->isValid(), validates an object rather than a form. Thus, to prevent This value should not be null. validation error I have to set value of those fields before validating the form. How to achieve this?


My controller:

  public function article_edit($action, Request $request)
        {
    $form = $this->createForm(ArticleType::class);  

        // Customize the form
        $form->remove("versionTimestamp");
        $form->remove("versionUserId");
        $form->remove("version");
        $form->add('save', SubmitType::class, ['label' => 'Zapisz']);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
        $article = $form->getData();
            /*
                $article->setVersionUserId($user);
                $article->setVersionTimestamp(new \DateTime());
                $article->setVersion(1);
            */
/.../

Solution

  • as Omar Makled commented, validation groups are one way to achieve this. TBH, I would prefer a different approach:

    $article = new Article();
    $article->setVersionUserId($user);
    $article->setVersionTimestamp(new \DateTime());
    $article->setVersion(1);
    
    $form = $this->createForm(ArticleType::class, $article); // <- preset
    $form->add('save', SubmitType::class, ['label' => 'Zapisz']);
    
    if ($form->isSubmitted() && $form->isValid()) {
        $article = $form->getData();
        // do other stuff...
    }
    

    (note: calling a field "userId" is weird, when you assign a User to it, but that's just me)