我会在控制器中分离逻辑。
在newWebsiteAction()
我显示我的表单。接下来,我将数据从表单发送到postWebsiteAction()
方法。
如果验证失败,我想重定向到senWebsiteAction()
并显示错误。我应该添加到我的代码中去做什么?因为现在我没有看到错误
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Website;
use AppBundle\Form\Type\WebsiteType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
class WebsitesController extends Controller
{
/**
* @Route("/websites", name="websites")
*/
public function getWebsiteAction()
{
return $this->render('websites/index.html.twig');
}
/**
* @Route("/websites/new", name="websites.new")
*/
public function newWebsiteAction()
{
$website = new Website();
$form = $this->createForm(new WebsiteType(), $website);
return $this->render('websites/create.html.twig', array(
'form' => $form->createView()
));
}
/**
* @Route("/websites/post", name="websites.post", methods={"POST"})
*/
public function postWebsiteAction(Request $request)
{
$form = $this->createFormBuilder()->getForm();
$form->handleRequest($request);
if($form->isValid())
{
$website = $form->getData();
$website->setUser($this->getUser());
$em =$this->getDoctrine()->getManager();
$em->persist($website);
$em->flush();
return $this->redirectToRoute('websites');
}
return $this->redirectToRoute('websites.new');
}
}
答案 0 :(得分:1)
嗯。恕我直言你做错了。
第一:你为什么不采取单一行动?如果你想要一些分离,最好将一些逻辑转移到服务上。因为服务中的存储逻辑是Symfony2方式。例如。对某些EntityManager服务(抽象示例)保持并刷新逻辑。
第二个(提示):如何在newWebsiteAction()
中获得$ form错误?
编辑:
以下是我通常这样做的方式:
public function createAction(Request $request)
{
$post = new Post();
$form = $this->createForm('post', $post);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
return $this->redirect($this->generateUrl('show_post', ['slug_title' => $post->getSlugTitle()]));
}
return $this->render('GeekhubMainBundle:Post:create.html.twig', ['form' => $form->createView()]);
}
是的,看起来某些逻辑会在不同的方法中重复,但是:
1)如果小于20行的方法都很好;
2)以你的方式处理句柄表单或创建实体的方法不可重复使用;
希望这会有所帮助:)
答案 1 :(得分:-2)
public function postWebsiteAction(Request $request)
{
$form = $this->createFormBuilder()->getForm();
$form->handleRequest($request);
if($form->isValid())
{
$website = $form->getData();
$website->setUser($this->getUser());
$em =$this->getDoctrine()->getManager();
$em->persist($website);
$em->flush();
return $this->redirectToRoute('websites');
} else {
$this->generateUrl('\your_defined_route');
return $this->redirect($url);
}
return $this->redirectToRoute('websites.new');
}
在$ form有效后查看else。