Search code examples
symfonyformbuilder

Exclude certain values in ManytoOne Array Colletion/Formbuilder


I am having trouble getting a formular in Symfony2 where I want to exclude certain values within an array collection - or I have to say I don't know how (where to exclude them).

This is my newTag Action:

public function newTagAction()
{
    $tag = new Tag();
    $form = $this->createForm(new tagType(), $tag);
    return $this->render('MyMyBundle:Admin:newTag.html.twig', array('form' => $form->createView()));

}

And Tag.php Entity, which has a ManyToOne relation to Movie and vice verca (Movie->Tag = OneToMany):

class Tag
{

/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;

/**
* @ORM\Column(type="string")
*/
protected $name;

/**
 * @ORM\ManyToOne(targetEntity="Movie", inversedBy="videotags")
 * @ORM\JoinColumn(name="movie_id", referencedColumnName="id")
 */
protected $movie;

// ...

In the TagType.php form it says:

class TagType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
    $builder
        ->add('name')
        ->add('movie') // This is where certain movies should be excluded, it displays an array collection of all movies 
    ;
}

Any help appreciated!

Thanks!


Solution

  • You can use custom queries to get only the results you want.

    It's explained in the documents. Here is a quick example:

    $builder->add('movie', 'entity', array(
        'class' => 'MyMovieBundle:Movie',
        'query_builder' => function(EntityRepository $er) {
            return $er->createQueryBuilder('u')
                ->where('u.name = ?1');
        },
    ));