Konrad Podgórski Web Developer / Software Architect

Place where I used to write about code related things. Currently umaintained.

How to implement a secure choice form field with Symfony

Please keep in mind that this post was written more than 2 years ago and might be outdated.

Create Util class for your entity, in my case entity is called 'Brand'

src/KP/Brand/MainBundle/Util/BrandUtil.php

    <?php

    namespace KP\Brand\MainBundle\Util;

    use KP\Brand\MainBundle\Entity\Brand;

    class BrandUtil
    {

        /**
         * @param bool $withLabels
         *
         * @return array
         */
        public static function getAvailableLanguageCodes($withLabels = false)
        {
            $choices = array(
                'pl' => 'Polish',
                'en' => 'English'
            );

            if ($withLabels) {
                return $choices;
            } else {
                return array_keys($choices);
            }
        }
    }

Create standard form type for your entity (I skipped required getName and setDefaultOptions methods here)

src/KP/Brand/MainBundle/Form/BrandType.php

    <?php

    namespace KP\Brand\MainBundle\Form;

    use KP\Brand\MainBundle\Util\BrandUtil;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolverInterface;

    class BrandType extends AbstractType
    {
        /**
         * @param FormBuilderInterface $builder
         * @param array $options
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('name')
                ->add(
                    'languageCode',
                    'choice',
                    array(
                        'label' => 'Language',
                        'choices' => BrandUtil::getAvailableLanguageCodes(true),
                    )
                );
        }

    }

src/KP/Brand/MainBundle/Resource/config/validation.yml

    KP\Brand\MainBundle\Entity\Brand:
    properties:
        languageCode:
            - Choice: { callback: [KP\Brand\MainBundle\Util\BrandUtil, getAvailableLanguageCodes] }

on

Find this post helpful? Spread the word, thanks.

Comments