在 Symfony2 中设置实体类型的默认值 [英] Set default value for entity type in Symfony2
问题描述
我不知道如何在 symfony2 中为实体类型设置默认值.我的代码如下所示:
I couldn't 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 in the object you are working with to make it work. My answer is below.
我在这方面找到了很多不同的答案,但它们都重构了表单的构建方式.这要容易得多.
I found a lot of different answers on this but they all restructured the way the form was built. This was much easier.
推荐答案
所以我找到了很多答案来完成这项工作,但他们似乎都重组了要以另一种方式构建的表单,但是我发现设置对象in 效果最好,所以我想我会发布我的解决方案,以防万一有人再次遇到这个问题.
So I found a lot of answers to make this work but all of them seemed to restructure the form to be built in another way however I found that setting the object in works best so I figured I would post my solution incase anyone ran into the issue 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();
我希望这能让事情变得更清楚.我看到了很多相同的问题,但没有使用此解决方案.
I hope this make things more clear. I saw a lot of the same question but none with this solution.
这篇关于在 Symfony2 中设置实体类型的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!