Php 在Symfony2中,您将如何执行此操作?
我有一个名为manageCountriesAction的控制器,在这里我从函数createCountryFormCountries$实体生成一个表单,并收到对createCountryAction函数的请求 现在,我不知道如何解决这个棘手的问题,如果表单无效或存在任何验证错误,我如何将它们重定向到manageCountriesAction并最终在模板中显示它们,例如:此字段不能为空 这是密码Php 在Symfony2中,您将如何执行此操作?,php,symfony,Php,Symfony,我有一个名为manageCountriesAction的控制器,在这里我从函数createCountryFormCountries$实体生成一个表单,并收到对createCountryAction函数的请求 现在,我不知道如何解决这个棘手的问题,如果表单无效或存在任何验证错误,我如何将它们重定向到manageCountriesAction并最终在模板中显示它们,例如:此字段不能为空 这是密码 <?php namespace CarsProject\BackendBundle\Contro
<?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;
}
}
在createCountryAction add-else-in中,如果您在其中选中$form->isValid,然后使用redirect或redirectToRoutehey@Robert重定向到此操作,则此操作不起作用,我在模板中没有收到表单验证错误。您是否声明了所有验证规则@我不确定,是我加的。如果确实需要在出错时重定向,则需要在会话中保存错误并再次将其拉出。只需遵循文档中的示例,并对get和post使用单个操作方法,就更容易了。