控制器必须 return 一个响应(给定 1 个)。 500 内部服务器错误 - LogicException

The controller must return a response (1 given). 500 Internal Server Error - LogicException

我从以下控制器代码开始

<?php

namespace AppBundle\Controller;

use AppBundle\Entity\events;
//use AppBundle\Entity\eventtype;
use AppBundle\Entity\users;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

class DefaultController extends Controller {

    /**
     * @Route("/home", name="homepage")
     */
    public function indexAction(Request $request) {
        $events = new events();

        $form = $this->createFormBuilder($events)
                ->add('eT1', ChoiceType::class, array(
                    'choices' => array(
                        'Poker' => 1,
                        'Chess' => 2,
                        'Cricket' => 3,
                        'Marbles' => 4,
                        'Football' => 5,
                    ),
                    'choices_as_values' => true,
                    'expanded' => true,
                    'multiple' => false,
                    'label' => 'Choose After Breakfast Event',
                ))
                ->add('eT2', ChoiceType::class, array(
                    'choices' => array(
                        'Poker' => 1,
                        'Chess' => 2,
                        'Cricket' => 3,
                        'Marbles' => 4,
                        'Football' => 5,
                    ),
                    'choices_as_values' => true,
                    'expanded' => true,
                    'multiple' => false,
                    'label' => 'Choose After Snacks Event',
                ))
                ->add('save', SubmitType::class, array('label' => 'Submit'))
                ->getForm();

        if ($request->isMethod('POST')) {
            $form->submit($request);

            $formData = $form->getData();

            //check to see if the after breakfast event (eT1) is full (ie.has reached the maxlimit)
            //for now the maxLimit is set to 4
            $ET1 = $formData->getET1();

            $repository = $this->getDoctrine()->getRepository('AppBundle:events');
            $query1 = $repository->createQueryBuilder('p')
                    ->select('count(p)')
                    ->where('p.eT1 = :eT1')
                    ->setParameter('eT1', $ET1)
                    ->getQuery();
            $a = $query1->getSingleScalarResult();

            if ($a >= $maxLimit=4) {
                echo 'choose another event, this one is full';
            }
            else{
               return $ET1; 
            }

            //check to see if the after snacks event (eT2) is full (ie.has reached the maxlimit)
            //for now the maxLimit is set to 4
            $ET2 = $formData->getET2();

            $query2 = $repository->createQueryBuilder('p')
                    ->select('count(p)')
                    ->where('p.eT2 = :eT2')
                    ->setParameter('eT2', $ET2)
                    ->getQuery();
            $b = $query2->getSingleScalarResult();

            if ($b >= $maxLimit=4) {
                echo 'choose another event, this one is full';
            }
            else{
               return $ET2; 
            }

            //get the user_id of the logged in user
            $user = $this->container->get('security.context')->getToken()->getUser();
            $events->setUser($user);
            $x = $events->getUser()->getID();

            if ($form->isValid()) {

                //check if the user has already registered or not
                $y = $repository->findOneBy(array('user' => $x));

                // If the user is registering for the first time (execute the insert query)
                if (!$y) {                    
                    $em = $this->getDoctrine()->getManager();
                    $em->persist($events);
                    $em->flush();
                    return $this->redirectToRoute('homepage');
                } 

                //If the user has registered already and want change his registered events (execute the update query)
                else {                    
                    $formData = $form->getData();
                    $ET1 = $formData->getET1();
                    $ET2 = $formData->getET2();
                    $events->setET1($ET1);
                    $events->setET2($ET2);

                    $em = $this->getDoctrine()->getManager();
                    $em->persist($events);
                    $em->flush();
                    return $this->redirectToRoute('homepage');
                }
            }
        }

        return $this->render('default/index.html.twig', array(
                    'form' => $form->createView(),
        ));
    }

}

但后来我修改了代码,为已经注册的用户和第一次注册的用户显示不同的页面。 以下代码给出错误 - 控制器必须 return 响应(给定 1)。 500 内部服务器错误 - LogicException 我的猜测是错误在于语句 return $ET1;return $ET2; 以下是我找不到答案的问题: 1. 错误原因 - 控制器必须 return 响应(给出 1)。 500 内部服务器错误 - LogicException 2. 我必须为新用户和已注册用户重复相同的代码两次。有解决办法吗? 3. 如何从 config.yml 文件中为不同的事件(例如扑克=12、国际象棋=4、板球=10 等)设置不同的 $maxLimit 参数值?

这里是修改后的控制器代码

<?php

namespace AppBundle\Controller;

use AppBundle\Entity\events;
//use AppBundle\Entity\eventtype;
use AppBundle\Entity\users;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

class DefaultController extends Controller {

    /**
     * @Route("/home", name="homepage")
     */
    public function indexAction(Request $request) {
        $events = new events();
        // check if the user is registering for the first time or else
        $user = $this->container->get('security.context')->getToken()->getUser();
        $events->setUser($user);
        $x = $events->getUser()->getID();

        $repository = $this->getDoctrine()->getRepository('AppBundle:events');
        $y = $repository->findOneBy(array('user' => $x));

        // If the user is registering for the first time (execute the insert query)
        if (!$y) {
            echo 'Welcome to the Birthday party';
            echo 'You can choose from the below options:';

            $form = $this->createFormBuilder($events)
                    ->add('eT1', ChoiceType::class, array(
                        'choices' => array(
                            'Poker' => 1,
                            'Chess' => 2,
                            'Cricket' => 3,
                            'Marbles' => 4,
                            'Football' => 5,
                        ),
                        'choices_as_values' => true,
                        'expanded' => true,
                        'multiple' => false,
                        'label' => 'After Breakfast Event',
                    ))
                    ->add('eT2', ChoiceType::class, array(
                        'choices' => array(
                            'Poker' => 1,
                            'Chess' => 2,
                            'Cricket' => 3,
                            'Marbles' => 4,
                            'Football' => 5,
                        ),
                        'choices_as_values' => true,
                        'expanded' => true,
                        'multiple' => false,
                        'label' => 'After Snacks Event',
                    ))
                    ->add('save', SubmitType::class, array('label' => 'Submit'))
                    ->getForm();

            if ($request->isMethod('POST')) {
                $form->submit($request);

                $formData = $form->getData();

                //check to see if the after breakfast event (eT1) is full (ie.has reached the maxlimit)
                $ET1 = $formData->getET1();

                $repository = $this->getDoctrine()->getRepository('AppBundle:events');
                $query1 = $repository->createQueryBuilder('p')
                        ->select('count(p)')
                        ->where('p.eT1 = :eT1')
                        ->setParameter('eT1', $ET1)
                        ->getQuery();
                $a = $query1->getSingleScalarResult();
//            var_dump($a);
//            exit;
                if ($a >= $maxLimit = 4) {
                    echo 'choose another event, this one is full';
                } else {
                    return $ET1;
                }

                //check to see if the after snacks event (eT2) is full (ie.has reached the maxlimit)
                $ET2 = $formData->getET2();

                $query2 = $repository->createQueryBuilder('p')
                        ->select('count(p)')
                        ->where('p.eT2 = :eT2')
                        ->setParameter('eT2', $ET2)
                        ->getQuery();
                $b = $query2->getSingleScalarResult();
//            var_dump($a);
//            exit;
                if ($b >= $maxLimit = 4) {
                    echo 'choose another event, this one is full';
                } else {
                    return $ET2;
                }

                if ($form->isValid()) {

                    $em = $this->getDoctrine()->getManager();
                    // tells Doctrine you want to (eventually) save the Product (no queries yet)
                    $em->persist($events);

                    // actually executes the queries (i.e. the INSERT query)
                    $em->flush();
                    return $this->redirectToRoute('homepage');
                }
            }
        }
        // If the user has registered already and want change his registered events (execute the update query)
        else {
            echo 'Welcome back';
            echo 'You registered for:';
            echo 'After Breakfast event:.$eventName.';
            echo 'After Snacks event:.$eventName.';
            echo 'You can change your selection by choosing again from below options:';

            $form = $this->createFormBuilder($events)
                    ->add('eT1', ChoiceType::class, array(
                        'choices' => array(
                            'Poker' => 1,
                            'Chess' => 2,
                            'Cricket' => 3,
                            'Marbles' => 4,
                            'Football' => 5,
                        ),
                        'choices_as_values' => true,
                        'expanded' => true,
                        'multiple' => false,
                        'label' => 'After Breakfast Event',
                    ))
                    ->add('eT2', ChoiceType::class, array(
                        'choices' => array(
                            'Poker' => 1,
                            'Chess' => 2,
                            'Cricket' => 3,
                            'Marbles' => 4,
                            'Football' => 5,
                        ),
                        'choices_as_values' => true,
                        'expanded' => true,
                        'multiple' => false,
                        'label' => 'After Snacks Event',
                    ))
                    ->add('save', SubmitType::class, array('label' => 'Submit'))
                    ->getForm();

            if ($request->isMethod('POST')) {
                $form->submit($request);

                $formData = $form->getData();

                //check to see if the after Breakfast event (eT1) is full (ie.has reached the maxlimit)
                $ET1 = $formData->getET1();

                $repository = $this->getDoctrine()->getRepository('AppBundle:events');
                $query1 = $repository->createQueryBuilder('p')
                        ->select('count(p)')
                        ->where('p.eT1 = :eT1')
                        ->setParameter('eT1', $ET1)
                        ->getQuery();
                $a = $query1->getSingleScalarResult();
//            var_dump($a);
//            exit;
                if ($a >= $maxLimit = 4) {
                    echo 'choose another event, this one is full';
                } else {
                    return $ET1;
                }

                //check to see if the after snacks event (eT2) is full (ie.has reached the maxlimit)
                $ET2 = $formData->getET2();

                $query2 = $repository->createQueryBuilder('p')
                        ->select('count(p)')
                        ->where('p.eT2 = :eT2')
                        ->setParameter('eT2', $ET2)
                        ->getQuery();
                $b = $query2->getSingleScalarResult();
//            var_dump($a);
//            exit;
                if ($b >= $maxLimit = 4) {
                    echo 'choose another event, this one is full';
                } else {
                    return $ET2;

                    if ($form->isValid()) {

                        $formData = $form->getData();
                        $ET1 = $formData->getET1();
                        $ET2 = $formData->getET2();
                        $events->setET1($ET1);
                        $events->setET2($ET2);
                        $em = $this->getDoctrine()->getManager();

                        $em->persist($events);
                        $em->flush();
                        return $this->redirectToRoute('homepage');
                    }
                }
            }
        }
        return $this->render('default/index.html.twig', array(
                    'form' => $form->createView(),
        ));

    }

}

下面是用户实体

<?php

namespace AppBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * users
 *
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\usersRepository")
 */
class users extends BaseUser
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Get id
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @ORM\OneToOne(targetEntity="events", mappedBy="user")
     */
    protected $event;


//    public function __construct()
//    {
//        parent::__construct(); 
//         }

    }

下面是事件实体

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
//use Symfony\Component\Validator\Constraints as Assert;

/**
 * events
 *
 * @ORM\Table(name="events")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\eventsRepository")
 */
class events {

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var int
     *
     * @ORM\Column(name="ET1", type="integer")
     */
    protected $eT1;

    /**
     * @var int
     *
     * @ORM\Column(name="ET2", type="integer")
     */
    protected $eT2;

    /**
     * @ORM\OneToOne(targetEntity="users", inversedBy="event")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
        protected $user;

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Set user
     *
     * @param users $user
     * @return events
     */
    public function setUser($user) {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return events
     */
    public function getUser() {
        return $this->user;
    }


    /**
     * Set eT1
     *
     * @param integer $eT1
     * @return events
     */
    public function setET1($eT1) {
        $this->eT1 = $eT1;

        return $this;
    }

    /**
     * Get eT1
     *
     * @return integer 
     */
    public function getET1() {
        return $this->eT1;
    }

    /**
     * Set eT2
     *
     * @param integer $eT2
     * @return events
     */
    public function setET2($eT2) {
        $this->eT2 = $eT2;

        return $this;
    }

    /**
     * Get eT2
     *
     * @return integer 
     */
    public function getET2() {
        return $this->eT2;
    }

//    public function __construct()
//    {
//        parent::__construct();
//    }
}

您的控制器不可读...您可能希望将业务代码放在服务中,将 formTypes 放在专用 类 中,将查询放在存储库 类.

我认为你没有进入 if(!$y ) 条件

放在最后:

return $this->render('default/index.html.twig'));

$ET2$ET2 这样的元素不是响应而是 formData 数组,Symfony 希望你 return 响应所以确保将它渲染到视图中,或者可能 return 通过新的 JsonResponse 对象将其作为数据?

您还可以添加 @Template annotation 以便能够 return 数据。该注释告诉 Symfony 应该根据 returned 数据呈现模板。

回答你的第一个问题:控制器必须总是 return 类型响应的对象,如果它不能 return 响应对象那么它必须通过执行内部子请求转发控制到执行 return 响应对象的控制器。在 symfony 中,twig 模板用于向用户显示输出,使用

return $this->render('navigation/homepage.html.twig', array('et1' => $et1, 'et2' => $et2));

将使两个变量 et1 和 et2 在 homepage.html.twig 模板中可用。

回答第二个问题:通过 $this->getUser() 获取当前登录用户,这是 security.context 令牌 link

的快捷方式

我在这里猜测,你试图检查 userId 是否与 'events' 对象的 userId 匹配,你认为它是一个 returning 用户,如果在此前提下,它不是新用户

$user = $this->getUser()->getUserId();
$event = $this->getDoctrine()->getRepository('AppBundle:events')->findOneBy(array('user' => $this->getUser()->getUserId() ));
if($event instanceof events){ //events refers to 'events' entity
// code to handle returning user
}

第三个问题的答案:避免使用全局变量,通过使用 config.yml 存储 maxValue,您使 maxValue 可用于整个项目。您可以更改代码中的内容以不使用 golbal 变量,但只是为了回答问题

将您的全局变量存储在 parameters.yml 而不是 config.yml 中只是为了让事情易于理解,做这样的事情 link

parameters:
    cricketMaxLimit: 10

$cricMaxLimit = $this->container->getParameter('cricketMaxLimit');

检索

旁注:像 if ($a >= $maxLimit = 4) 这样的东西在这个世界上根本不应该存在,做 if ($a >= 4)

-dheeraj :)