Matt Welander
Matt Welander

Reputation: 8548

symfony2 form field: entity with custom option name

I use entity for form field type, and get my list of options for that dropdownbox like this, works like a charm.

    $builder->add('parent', 'entity', array(
    'label' => 'Välj en fastighet för skärmen ',
    'class' => 'BizTVContainerManagementBundle:Container','property'=>'name',
    'query_builder' => function(EntityRepository $er) use ($parentType, $company) {
        return $er->createQueryBuilder('u')
            ->where('u.containerType = :type', 'u.company = :company')
            ->setParameters( array('type' => $parentType, 'company' => $company) )
            ->orderBy('u.name', 'ASC');
        },
    ));

Now, how can I customize the display name to be something I code together, instead of just the

'property'=>'name

What I would ultimately want to do is to have the currently displayed string, coupled with another string. I actually want to get this entity's parent's name in there as well, something like:

option_name = $entity->getName() . ' (' . $entity->getParent()->getName() . ')' .

Would be an easy thing if i had built the form myself, flat php html, but since I don't like to do hundreds of dull hours, I like to use symfony2 these days =)

any input welcome...

Upvotes: 1

Views: 1610

Answers (1)

gremo
gremo

Reputation: 48909

Modify your Container class and add a method for returning your string (as you prefer):

class Container
{
    public function getSelectLabel()
    {
        return $this->name . '(' . $this->parent->getName() . ')';

    }
}

And then use it as property (just replace the case with _ followed by lower case):

$builder->add('parent', 'entity', array(
    'label'    => 'Välj en fastighet för skärmen ',
    'class'    => 'BizTVContainerManagementBundle:Container'
    'property' => 'select_label',
));

So getSelectLabel() becomes "select_label", without "get".

Upvotes: 4

Related Questions