Symfony2 choice field not working

删除回忆录丶 提交于 2019-12-03 16:26:57
StrikoMirko

Ok i managed to resolve the dilemma. The answer was easy all I had to do is change

$builder->add('parent', 'choice', array(
 'choices' => $this->getAllChildren($catID),
 'required' => false,
 'attr'   =>  array('data-placeholder' => '--Izaberite Opciju--'),
));

to this:

 $builder->add('parent', 'entity', array(
                'class' => 'KprCentarZdravljaBundle:Category',
                'choices' => $this->getAllChildren($catID),
                'property' => 'name',
                'required' => false,
                'attr'   =>  array('data-placeholder' => '--Izaberite Opciju--'),
                ));

And change the getAllChildren(..) function so that it returns objects

private function getAllChildren($catID)
{
    $choices = array();
    $children = $this->doctrine->getRepository('KprCentarZdravljaBundle:Category')->findByParenting($catID);

    foreach ($children as $child) {
        $choices[$child->getId()] = $child->getName();
    }

    return $choices;
}

I changed it to:

private function getAllChildren($catID)
{
    $children = $this->doctrine->getRepository('KprCentarZdravljaBundle:Category')->findByParenting($catID)

    return $children;
}

Lots of thanks to user redbirdo for pointing out the choices option on an entity field.

It seems like you are doing something too much complicated.
You are on the right way when you write Symfony framework is expecting an entity field instead of choice field.

To do this, replace:

$builder->add('parent', 'choice', array(
     'choices' => $this->getAllChildren($catID),
     'required' => false,
     'attr'   =>  array('data-placeholder' => '--Izaberite Opciju--'),
));

by:

$builder->add('users', 'entity', array(
    'class' => 'KprCentarZdravljaBundle:Category',
    'property' => 'name',
    'query_builder' => function(EntityRepository $er) use($catID) {
        return $er->findByParenting($catID);
    },
    'required' => false,
    'empty_value' => '--Izaberite Opciju--'
));

(and you don't need getAllChildren($catID) anymore unless used somewhere else)

http://symfony.com/doc/current/reference/forms/types/entity.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!