1

In symfony2 I have an entity Foo which has a field named $kind that can have some(at most about 10) different values(one at each time) something like this:

$kindArray('1' => 'type1', '2'=> 'type2');

and $kind field can get one of $kindArray indices.

I want one location that have $kindArray and use it for choiceType values when creating FooFormType.

how can I show it in entity? should I use array or something like value object?

2 Answers 2

3

Entity definition

You can store these kinds as constants in entity class.

class Foo
{
  const KIND_1 = 1;
  const KIND_2 = 2;
  const KIND_3 = 3;
  //...

  /**
   * @ORM\Column(type="smallint")
   */
  protected $kind;
}

Note that constants are integers, so they are easy stored in database. I used smallint because it's the smallest integer available in Doctrine2.

Form

Create new form field for kind:

class KindChoiceType extends AbstractType
{

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $class = new \ReflectionClass('Namespace\Bar\Foo');
        $resolver->setDefaults(array(
            'choices' => array_flip($class->getConstants()),
            'translation_domain' => 'kinds' 
        ));
    }

    public function getName()
    {
        return 'kind_choice';
    }

    public function getParent()
    {
        return 'choice';
    }

}

'Namespace\Bar\Foo' is full name of your entity class with namespace. (Note that work only because all constants in class are kinds. If you will add another constants, you must modify that code.)

Now create translation files for all languages of your website. I usually create YAML file. For English it should look like:

# YOUR_BUNDLE/Resources/translations/kinds.en.yml

KIND_1: first kind
KIND_2: kind no. 2
KIND_3: next kind
# ...

Now pass your new field type instead of 'choice' when you create form for your Foo entity:

->add('kind', new KindChoiceType());
Sign up to request clarification or add additional context in comments.

Comments

0

You could have the states as constants and then return them in a static method like so..

class Thing
{
    const STATE_1 = 'state_1';
    const STATE_2 = 'state_2';
    const STATE_3 = 'state_3';

    public static function getAllStates()
    {
        return array(
            self::STATE_1,
            self::STATE_2,
            self::STATE_3,
        );
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.