在 Symfony 3 中获取实体类型的值 [英] Get values of Entity Type in Symfony 3
问题描述
如何获取控制器中下拉字段的值.
How do I get the value of dropdown field in controller.
我有下拉字段,其中数据值来自数据库中的一个表.请看下面的代码.
I have drop down fields where values of data is from one of my table in database. Please see the code below.
class SubAgentType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('company_id', EntityType::class, array(
'label' => 'Company',
'required' => true,
'class' => 'SwipeBundle:Company',
'choice_label' => 'name',
'expanded' => false,
'multiple' => false,
'placeholder' => 'Choose a Company',
'constraints' => array(
new NotBlank(array("message" => 'Company name is required.')),
),
)); ../
在我的 html.twig 中它工作正常,它正确呈现 html,而有一个数值数字和公司名称.
In my html.twig it works fine, it renders the html correctly whereas there's a value numeric and the name of company.
更新:
<select id="sub_agent_company_id" name="sub_agent[company_id]" required="required">
<option value="" selected="selected">Choose a Company</option>
<option value="20">20 Incorporated</option>
<option value="21">21</option>
<option value="22">22</option>
</select>
问题是实体类型返回的是类公司对象,而不是仅返回下拉列表的值.
The problem is the entity type is returning the class company object instead of the value of a dropdown only.
如何只获取下拉列表的值而不是对象?
How do I get only the values of dropdown instead an object?
这是我的下拉 companyid [![enter image description here][1]][1] 中错误的屏幕截图
here's the screenshot of error in my dropdown companyid [![enter image description here][1]][1]
推荐答案
我猜你需要在 choice_label
内部使用一个匿名函数,才能得到 id
s.而且我还认为你应该重命名字段名称,而不是 company_id
简单地输入 company
.
I guess you need to use an anonymous function inside choice_label
, in order to get the id
s. And I also think you should rename the field name, and instead of company_id
simply put company
.
$builder->add('company', EntityType::class, array(
//...
'choice_label' => function($company){
return $company->getId();
},
//...
此外,您可能需要在此代码中使用 query_builder
选项,但是在尝试我编写的代码后,您将稍后告诉我们这一点.
Moreover, you may need to use the query_builder
option inside this code, but this thing you'll gonna tell us later, after trying the code I wrote.
乐
对于 query_builder
.
use use Doctrine\ORM\EntityRepository;
//...
$builder->add('company', EntityType::class, array(
//...
`query_builder` => function(EntityRepository $er){
return $er->createQueryBuilder('c');
},
'choice_label' => function($company){
return $company->getId();
},
//...
这篇关于在 Symfony 3 中获取实体类型的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!