简体   繁体   中英

Remove empty options in dropdown in Symfony 3.4

I have created a form which populates a dropdown with Users who fit a particular criteria. However, the entire array of users is sent through but the entries that do not fit the criteria are blank, so I have a dropdown with lots of blank options in, which I do not want. Looking at other stackoverflow questions 'placeholder' and 'empty_values' are employed but these do not seem to work.

here is the code from the form:

        ->add(
            'userParent',
            EntityType::class,
            [   
                'class' => User::class,
                'choice_label' => function ($parents) {
                    return $parents->getUniqueName();
                }

            ]
        )

and the getUniqueName function:

    public function getUniqueName() {

    $name = "";

    $nameBlock = json_decode($this->name, true);
    if (is_array($nameBlock) && isset($nameBlock['name'])) {
        $name = $nameBlock['name'];  
    } 
    return $name;
}

My bad, I read too fast.

Since your field is serialized, you can't go either with a custom query filtering your entities without name, but if your form is displayed, you can still ignore empty names at the rendering. Through form themes for example, by overriding default choice_type theme, or setting a custom block_name for your field and creating the associated theme, see https://symfony.com/doc/current/form/form_customization.html#form-theming-in-twig and https://symfony.com/doc/current/reference/forms/types/form.html#block-name

->add(
        'userParent',
        EntityType::class,
        [   
            'class' => User::class,
            'query_builder' => function (\Doctrine\ORM\EntityRepository $repository) {
                    // fetch data from the repository based on your criteria
                    return $repository->findUsersFunction();

                    //or create the query right here
                    //return $er->createQueryBuilder('u')->where(); ...
                }

        ]
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM