我有一个名为manageCountriesAction
的控制器,我从函数createCountryForm(Countries $entity)
生成一个表单,然后我收到Request
到createCountryAction
函数。
现在是一个棘手的部分,我不知道如何弄清楚,如果表单无效或有任何验证错误,我可以将它们重定向到manageCountriesAction
和最后在模板中显示它们(例如:这个字段不能为空)?
这是代码
<?php
namespace CarsProject\BackendBundle\Controller;
use CarsProject\BackendBundle\Entity\Countries;
use CarsProject\BackendBundle\Form\CountriesType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class AdminPanelController extends Controller
{
/**
* Locations: manage countries controller
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function manageCountriesAction()
{
$em = $this->getDoctrine()->getEntityManager();
$countries = $em->getRepository('CarsProjectBackendBundle:Countries')->findAll();
$newEntity = new Countries();
$formNewCountry = $this->createCountryForm($newEntity);
return $this->render('CarsProjectBackendBundle:Backend:manage_countries.html.twig', array(
'countries_entity' => $countries,
'form_new_country' => $formNewCountry->createView()
));
}
/**
* Create action for Countries Entity
*
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function createCountryAction(Request $request)
{
$entity = new Countries();
$form = $this->createCountryForm($entity);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirectToRoute('cars_project_backend_manage_countries');
}
/* *
* If submitted data or $form isn't valid then redirect the response (form validation errors)
* to "manageCountriesAction" controller and finally make the validation errors appear
* in the twig template of "manageCountriesAction" controller.
**/
}
/**
* Create form for Countries Entity
*
* @param Countries $entity
* @return \Symfony\Component\Form\Form
*/
public function createCountryForm(Countries $entity)
{
$form = $this->createForm(new CountriesType(), $entity, array(
'action' => $this->generateUrl('cars_project_backend_manage_countries_form_new'),
'method' => 'POST'
));
return $form;
}
}