Skip to content

Instantly share code, notes, and snippets.

@konradpodgorski
Created October 19, 2013 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save konradpodgorski/7053983 to your computer and use it in GitHub Desktop.
Save konradpodgorski/7053983 to your computer and use it in GitHub Desktop.
How to implement a secure choice form field with Symfony

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] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment