1

I have an Entity called "InterestGroup" that has a self referencing association (adjacency list) in the form of properties "children" (one to many) and "parent" (many to one).

In setting up a form type for InterestGroup, I'm attempting to provide a select list for the property parent, that has choices of all 'top level' interest groups (those whose 'parent' property is null). When I add the the where clause and null parameter to the query_builder for the EntityType field, it always returns nothing, even when I have several top level (parent is null) interest groups persisted. If I remove the where clause it will return all InterestGroups in the table. I'm having a difficult time understanding why the where clause is not working.

This is the field in question:

->add('parent',EntityType::class,
    array(
        'placeholder' => 'Top Level (No Parent)',
        'required' => false,
        'class' => 'Common\ContentBundle\Entity\InterestGroup',
        'query_builder' => function (EntityRepository $er) {
            return $er->createQueryBuilder('ig')
              ->where('ig.parent = :n')
              ->setParameter('n',null)
              ->orderBy('ig.title', 'ASC');
        },
        'choice_label' => 'title'
    )
)

The above will return an empty select menu. By removing the where clause and the setparameter, I get all the InterestGroup Entities including all those that have null parents.

Following is the Entity Class for InterestGroup

<?php

namespace Common\ContentBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * InterestGroup
 *
 * @ORM\Table(name="interest_group")
 * @ORM\Entity(repositoryClass="Common\ContentBundle\Repository\InterestGroupRepository")
 */
class InterestGroup
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255, unique=true)
     * @Assert\NotBlank(message="This is a required field.")
     */
    private $title;

    /**
     * @ORM\OneToMany(targetEntity="InterestGroup", mappedBy="parent")
     */
    private $children;

    /**
     * @ORM\ManyToOne(targetEntity="InterestGroup", inversedBy="children")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
     */
    private $parent;

    /**
     * @Gedmo\Slug(fields={"title"})
     * @ORM\Column(length=128, unique=true)
     */
    private $slug;

    // ...
    /**
     * @ORM\ManyToMany(targetEntity="Product", mappedBy="interestGroups")
     */
    private $products;


    /**
     * InterestGroup constructor.
     */
    public function __construct()
    {
        $this->children = new ArrayCollection();
        $this->products = new ArrayCollection();

    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }


    /**
     * @return mixed
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * @return mixed
     */
    public function getChildren()
    {
        return $this->children;
    }

    /**
     * @param mixed $children
     */
    public function setChildren($children)
    {
        $this->children = $children;
    }

    /**
     * @return mixed
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * @param mixed $parent
     */
    public function setParent($parent)
    {
        $this->parent = $parent;
    }

    /**
     * @return mixed
     */
    public function getProducts()
    {
        return $this->products;
    }
}

And the Form Type Class:

<?php

namespace Common\ContentBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;

class InterestGroupType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title',TextType::class)
            ->add('parent',EntityType::class,
              array(
                'placeholder' => 'Top Level (No Parent)',
                'required' => false,
                'class' => 'Common\ContentBundle\Entity\InterestGroup',
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('ig')
                      ->where('ig.parent = :n')
                      ->setParameter('n',null)
                      ->orderBy('ig.title', 'ASC');
                },
                'choice_label' => 'title'
              )
            )
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Common\ContentBundle\Entity\InterestGroup'
        ));
    }
}

Thanks in advance!

Robert Wade
  • 4,918
  • 1
  • 16
  • 35

1 Answers1

2

Check you code here:

return $er->createQueryBuilder('ig')
          ->where('ig.parent = :n') // <---
          ->setParameter('n',null) // <--- 
          ->orderBy('ig.title', 'ASC');

It is the same to:

... WHERE ig.parent = NULL ...

So, this query always returns null dataset.

Right code:

return $er->createQueryBuilder('ig')
          ->where('ig.parent IS NULL')
          ->orderBy('ig.title', 'ASC');

Use IS NULL for checking null values.

This problem is related to what is "=null" and " IS NULL"

Community
  • 1
  • 1
yceruto
  • 9,230
  • 5
  • 38
  • 65