1

I can't figure out why Doctrine's ODM Unique constraint isn't working for me.

Below is a Page Class with the property "title", that needs to be unique amongst all Pages.

namespace App\Document;

use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Bundle\MongoDBBundle\Validator\Constraints\Unique as MongoDBUnique;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use App\Repository\PageRepository;
use App\Document\Embeded\Section;

/**
 * @ODM\Document(repositoryClass=PageRepository::class)
 * @MongoDBUnique(fields="title")
 */
class Page
{
    /** @ODM\Id() */
    private $id;

    /** @ODM\ReferenceOne(targetDocument=Site::class) */
    private $site;

    /** @ODM\Field(type="string")
     * @ODM\UniqueIndex(order="asc")
     */
    private $title;

    // ...

Within the controller, $form->handleRequest($request) is called, followed by the query: if ($form->isSubmitted() && $form->isValid())

The form is always returned as valid. The ODM Unique constraint seems to be ignored. I've also tried to add a custom Validation Constraint and was met with the same issue.

Do I need to add any additional configuration to get this to work?

yivi
  • 42,438
  • 18
  • 116
  • 138
Tim Newey
  • 21
  • 3

1 Answers1

1

Symfony forms only validate the top-level object by design. In this case, the Page Class was attached to an embedded form.

Solution: add Symfony's @Valid() constraint to the property, within the top-level object.

/** @ODM\ReferenceOne(targetDocument="App\Document\Page", cascade={"persist"}, orphanRemoval=true)
 * @ODM\Index 
 * @Assert\Valid()
 */
private $page;
Tim Newey
  • 21
  • 3