【发布时间】:2019-01-15 09:02:10
【问题描述】:
我不知道如何告诉我的表单类型类接受传入键/值数组的选择值函数参数。
这是我的表单类型 buildForm 函数的样子:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('tiers', ChoiceType::class, [
'choices' => $this->userSubscriptionTierRepository->getTiersSubscribedToByUser($this->userProvider->getCurrentUser()),
'choice_label' => 'name',
'required' => false,
'multiple' => true,
'expanded' => false,
'attr'=> array('class'=>'custom-select'),
'choice_value' => function (array $val /* this is wrong */) {
return $val['tierNumber'];
}
])
;
}
在底部,'choice_value' 所在的位置,我不知道如何正确声明函数以接受传入的值。
下面是选项“getTiersSubscribedToByUser”函数的样子:
/**
* @param User $user
* @return array
*/
public function getTiersSubscribedToByUser(User $user) : array
{
$qb = $this->createQueryBuilder('t');
$qb->select('t.tierNumber, COUNT(t.tierNumber)')
->innerJoin('t.subscriptions', 'subscriptions', 'WITH', 'subscriptions.isCancelled != :true')
->where('subscriptions.subscriber = :user')
->groupBy('t.tierNumber')
->orderBy('t.tierNumber', 'ASC')
->setParameter('user', $user)
->setParameter('true', true);
$query = $qb->getQuery();
return $query->getResult();
}
getTiersSubscribedToByUser 的结果如下所示:
array:3 [▼
0 => array:2 [▼
"tierNumber" => 1
1 => "2"
]
1 => array:2 [▼
"tierNumber" => 2
1 => "1"
]
2 => array:2 [▼
"tierNumber" => 3
1 => "1"
]
]
所以我必须告诉表单类型类选择值以接受如下所示:
1 => array:2 [▼
"tierNumber" => 2
1 => "1"
我该怎么做?
它给了我错误:
Argument 1 passed to App\Form\FeedFilterType::App\Form\{closure}() must be of the type array, integer given
【问题讨论】:
-
你试过dump()数组$val吗?只需删除
array部分并放置一个 dump() 和一个 exit 以查看其值。 -
If there are choice values that are not scalar or the stringified representation is not unique Symfony will use incrementing integers as values. When the form gets submitted the correct values with the correct types will be assigned to the model.symfony.com/doc/4.1/reference/forms/types/choice.html#choices -
JorgeeFG,我尝试转储并得到数字“1”。但这仍然不能解决我的问题。
标签: forms function symfony choice