php – 在Symfony2中设置实体类型的默认值

前端之家收集整理的这篇文章主要介绍了php – 在Symfony2中设置实体类型的默认值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我无法弄清楚如何在symfony2中为实体类型设置默认值.我的代码看起来像这样:
$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();

但是,您需要交出正在使用的对象才能使其正常工作.我的答案如下.

我发现了很多不同的答案,但他们都重新构建了表单的构建方式.这更容易.

所以我找到了很多答案来使这项工作,但所有这些似乎重新组织形式以另一种方式构建,但我发现设置对象最好的工作,所以我想我会发布我的解决方案任何人遇到问题再次.

这是我在控制器中的代码.

// 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',// 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();

我希望这会让事情更清楚.我看到很多相同的问题,但没有这个解决方案.

原文链接:https://www.f2er.com/php/133194.html

猜你在找的PHP相关文章