如何在表单中列出查询结果(EntityType)

时间:2017-05-26 18:19:25

标签: php symfony doctrine-orm symfony-forms query-builder

在我的项目中,我使用数据表格一个表(用户任务)来描述创建预订记录(预订表)的数据。在表单中,我尝试收到选择列表。

运行时出现错误:
  

Expected argument of type "Doctrine\ORM\QueryBuilder", "array" given

为什么"阵列"数据有误吗?有什么变化?

我的代码:

形式:

<?php
namespace AppBundle\Form;
use AppBundle\Repository\TaskRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class ReservationType
 *
 * @package AppBundle\Form
 */
class ReservationType extends AbstractType
{
  /**
   * {@inheritdoc}
   */
  public function buildForm( FormBuilderInterface $builder, array $options )
  {
    $builder
      ->add( 'taskId', EntityType::class, [
        'class' => 'AppBundle:Task',
        'query_builder' => function (TaskRepository $tr) use ($options) {
          return $tr->TaskUserListQuery( $options['userId']);
        },
        'attr' => [
          'data-type' => 'text',
          'class' => 'table-select',
          'disabled' => true
        ],
        'required' => false
      ])
    ;
  }

  /**
   * {@inheritdoc}
   */
  public function configureOptions( OptionsResolver $resolver )
  {
    $resolver->setDefaults( [
                  'data_class' => 'AppBundle\Entity\Task',
                  'userId'  => null,
                ] );
  }


  /**
   * {@inheritdoc}
   */
  public function getBlockPrefix()
  {
    return 'appbundle_reservation';
  }
}

存储库:

<?php
namespace AppBundle\Repository;
use \Doctrine\ORM\EntityRepository;

/**
 * TaskRepository
 */
class TaskRepository extends EntityRepository
{
  /**
   * Function TaskUserListQuery
   * @return array
   */
  public function TaskUserListQuery( $userId )
  {
    return $this->createQueryBuilder( 't' )
      ->select(
        't.id',
        't.taskName'
      )
      ->orderBy( 't.id', 'ASC' )
      ->where( 't.userId = :par1' )
      ->setParameter( 'par1', $userId )
      ->getQuery()
      ->getResult();
  }
}

控制器:

<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Reservation;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;

/**
 * Reservation controller.
 *
 * @Route("/re")
 */
class ReservationController extends Controller
{

  /**
   * Creates a new reservation entity.
   *
   * @Route("/new", name="r_new")
   * @Method({"GET", "POST"})
   */
  public function newAction( Request $request )
  {
    $userId = 1;

    $reservation = new Reservation();
    $tableForm = $this->createForm( 'AppBundle\Form\ReservationType', $reservation, [
      'userId' => $userId,
    ] );
    $form = $tableForm->createView();
    $form->handleRequest( $request );

    if ($form->isSubmitted() && $form->isValid()) {
      $em = $this->getDoctrine()->getManager();
      $em->persist( $reservation );
      $em->flush();

      return $this->redirectToRoute( 'r_show', [ 'id' => $reservation->getId() ] );
    }

    return $this->render( 'reservation/new.html.twig', [
      'reservation'  => $reservation,
      'form'     => $form->createView(),
    ] );
  }

   // (... more)

}

当我犯错误时?

我学习表单示例并在Symfony 3.2上运行。 请帮我。

2 个答案:

答案 0 :(得分:2)

此外,您无法在handleRequest对象上调用FormView方法。

$tableForm = $this->createForm( 'AppBundle\Form\ReservationType',
    $reservation, ['userId' => $userId,]);
$form = $tableForm->createView(); // WTF ?
$form->handleRequest( $request );

TaskRepository

public function TaskUserListQuery( $userId )
{
    return $this->createQueryBuilder( 't' )
        ->select('t') // in this way
        ->orderBy( 't.id', 'ASC' )
        ->where( 't.userId = :par1' )
        ->setParameter( 'par1', $userId );
}

在您使用选择的情况下('t.id',...) QueryBuilder将返回普通数组

array:1 [▼
  0 => array:2 [▼
    "id" => 1
    "task_name" => "New Task"
  ]
]

EntityType需要一组像

这样的对象
array:1 [▼
  0 => Task {#448 ▶}
]

最后,不要忘记在'choice_label' => 'task_name'方法中添加选项buildForm

答案 1 :(得分:1)

您应该将querybuilder对象实例而不是query_builder参数的结果返回为described in the doc here。所以改变你的repo方法如下:

  /**
   * Function TaskUserListQuery
   * @return QueryBuilder
   */
  public function TaskUserListQuery( $userId )
  {
    return $this->createQueryBuilder( 't' )
      ->select(
        't.id',
        't.taskName'
      )
      ->orderBy( 't.id', 'ASC' )
      ->where( 't.userId = :par1' )
      ->setParameter( 'par1', $userId );
  }

希望这个帮助