Set default value for object type in Symfony2

I could not figure out how to make a default value for an entity type in symfony2. My code looked like this:

$rewardChoice = $this->createFormBuilder($reward)
    ->add('reward_name', 'entity', array(
        'class' => 'FuelFormBundle:Reward',
        'property' => 'reward_name',
        'data' => 2,
        'query_builder' => function(EntityRepository $er){
            return $er->createQueryBuilder('r')
                ->where('r.active = 1')
                ->groupBy('r.reward_id')
                ->orderBy('r.reward_name', 'DESC');

        },
    ))
    ->getForm();

However, you need to hand over the object you are working with in order for it to work. My answer is below.

I found many different answers to this, but they all changed the way the form was created. It was a lot easier.

+4
source share
2 answers

So, I found a lot of answers to make this work, but they all seemed to restructure the form, which would be built differently, but I found that setting up the object in the work is best, so I decided that I would post my solution, if anyone wins the question again.

Here is my code in the controller.

// this is setting up a controller and really isn't important 
$dbController = $this->get('database_controller');

// this is getting the user id based on the hash passed by the url from the
// database controller
$user_id = $dbController->getUserIdByHash($hash);

// this is getting the Reward Entity.  A lot of times you will see it written as 
// $reward = new Reward however I am setting info into reward right away in this case
$reward = $dbController->getRewardByUserId($user_id);


$rewardChoice = $this->createFormBuilder($reward)
    ->add('reward_name', 'entity', array(
        'class' => 'FuelFormBundle:Reward',
        'property' => 'reward_name',

        // I pass $reward to data to set the default data.  Whatever you
        // assign to $reward will set the default value.  
        'data' => $reward,  
        'query_builder' => function(EntityRepository $er){
                return $er->createQueryBuilder('r')
                    ->where('r.active = 1')
                    ->groupBy('r.reward_id')
                    ->orderBy('r.reward_name', 'DESC');
        },
    ))
    ->getForm();

, . , .

+8

- . :

$reward->setRewardName('your_relationship_reference_here');

$rewardChoice = $this->createFormBuilder($reward)

data .

0

All Articles