簡體   English   中英

(Symfony 4表單)將非實體查詢結果傳遞給表單函數

[英](Symfony 4 Forms) Passing non-entity query results to a form function

我不知道如何告訴我的表單類型類接受傳入鍵/值數組的choice_value函數參數。

這是我的表單類型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

選擇價值將為您提供他所說的確切內容,即每個選擇的價值。 如果您要根據給定的數組發送$val['tierNumber'] ,則您將獲得一個整數,該整數為true,但它需要一個數組。

根據文檔的choice_value

 This can be a callable or a property path. If null is given, an incrementing integer is used as the value. If you pass a callable, it will receive one argument: the choice itself. 

由於您不使用EntityType,因此不需要處理choice_value,因為您的選擇不是對象:

如果傳遞可調用對象,它將收到一個參數:選擇本身。 使用EntityType字段時,參數將是每個選擇的實體對象,在某些情況下將為null,您需要處理:

'choice_value' => function (MyOptionEntity $entity = null) {
    return $entity ? $entity->getId() : '';
},

您是否嘗試過不使用choice_value?

此處的文檔: https : //symfony.com/doc/4.1/reference/forms/types/choice.html#choice-value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM