我有一个问题,要用Symfony和Doctrine制作一个搜索框。我使用的是Symfony的2.8版本。
我的问题是:
EntityManager#persist()要求参数1为实体对象,给定数组。500内部服务器错误-ORMInvalidArgumentException
所以,这是我的搜索框类型的类型:
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('searchBox',SearchType::class,array('label'=>'Vous cherchez : Un auteur ? Un éditeur ? Un ouvrage ?','attr'=>array('class'=>'form-control')));
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class1' => 'SBMainBundleEntityOuvrages',
'data_class2' => 'SBMainBundleEntityAuteurs',
'data_class3' => 'SBMainBundleEntityEditeurs'
));
}
这是我编辑后的控制器代码:
public function indexAction(Request $request) {
$ouvragesVentes = $this->getDoctrine()->getRepository('SBMainBundle:Ouvrages')->getOuvragesVentes();
$ouvragesEchanges = $this->getDoctrine()->getRepository('SBMainBundle:Ouvrages')->getOuvragesEchanges();
$categories = $this->getDoctrine()->getRepository('SBMainBundle:Categories')->getAllCats();
$form = $this->createForm(SearchBoxType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$searchBoxValue = $form->getData();
$bookName = $this->getDoctrine()->getRepository('SBMainBundle:Ouvrages')->getOuvrageName($searchBoxValue);
$editorName = $this->getDoctrine()->getRepository('SBMainBundle:Editeurs')->getEditeurName($searchBoxValue);
$autorName = $this->getDoctrine()->getRepository('SBMainBundle:Auteurs')->getAuteurName($searchBoxValue);
//if author
if ($searchBoxValue == $autorName){
return $this->redirect($this->generateUrl('sb_main_auteur'));
}
//if editor
if ($searchBoxValue == $editorName){
return $this->redirect($this->generateUrl('sb_main_editeur'));
}
//if book name
if ($searchBoxValue == $bookName){
return $this->redirect($this->generateUrl('sb_main_ouvrage'));
}
}
$datas = array('categories'=>$categories,'form'=>$form->createView(),'ouvragesEchanges'=>$ouvragesEchanges,'ouvragesVentes'=>$ouvragesVentes);
return $this->render('SBMainBundle:Main:index.html.twig',$datas);
}
编辑:我的表单处理程序
protected $request;
protected $form;
protected $em;
//faire une injection de dépendance avec Request,Manager,Form(Objet)
public function __construct(Request $request,EntityManager $em, Form $form){
$this->request = $request;
$this->em = $em;
$this->form = $form;
}
//vérifie si le formulaire est soumis et valide
public function process(){
if ($this->request->getMethod() == "POST"){
//récupération des données de la requête de la superglobale $_POST
$this->form->handleRequest($this->request);
//si ok, on appel onSuccess()
if ($this->form->isValid()){
$this->onSuccess($this->form->getData());
return true;
}
}
return false;
}
//si formulaire soumis et valide, on presiste l'objet (enregistre dans la DB)
public function onSuccess($object){
//on persiste dans la DB via le manager Doctrine
$this->em->persist($object);
$this->em->flush();
}
我看了一下,但我认为这不是解决我问题的办法。然后,有人可以告诉我怎么了?即使有搜索框,我也需要搜索框实体吗?
谢谢你的帮助!
编辑:
堆栈跟踪
in srcSBMainBundleRepositoryOuvragesRepository.php at line 130 -
public function getOuvrageName($titre){
$query = $this->getEntityManager()->createQuery(
"SELECT o FROM SBMainBundle:Ouvrages o WHERE o.titreOuvrage = $titre ORDER BY o.id DESC "
);
return $query->getResult();
at ErrorHandler ->handleError ('8', 'Array to string conversion', 'C:wampwwwswitchbooksrcSBMainBundleRepositoryOuvragesRepository.php', '130', array('titre' => array('searchBox' => 'flammarion')))
in srcSBMainBundleRepositoryOuvragesRepository.php at line 130 +
at OuvragesRepository ->getOuvrageName (array('searchBox' => 'flammarion'))
in srcSBMainBundleControllerMainController.php at line 35 +
at MainController ->indexAction (object(Request))
at call_user_func_array (array(object(MainController), 'indexAction'), array(object(Request)))
in vendorsymfonysymfonysrcSymfonyComponentHttpKernelHttpKernel.php at line 144 +
at HttpKernel ->handleRaw (object(Request), '1')
在vendor\symfony\symfony \src\symfony\Component\HttpKernel\HttpKernel.php的第64行+在HttpKernel->句柄(object(Request),'1',true)在vendor\symfony\symfony \src\symfony\Component\HttpKernel\DependencyInjection\ContainerwareHttpKernel.php的第69行+在ContainerwareHttpKernel->句柄(对象(请求),"1",true)在vendor\symfony\symfony \src\symfony\Component\HttpKernel\Kernel.php的第185行+在内核->句柄(对象(请求))在web\app_dev.php中,第28行+
新编辑:
缺少一些用于生成路由"sb_main_ouvrage"的URL的强制参数("titreOverrage")。
sb_main_ouvrage:
path: /ouvrage/{titreOuvrage}
defaults: { _controller: SBMainBundle:Main:ouvrage}
堆栈跟踪
在第911 行的app\cache\dev\classes.php中
$variables = array_flip($variables);
$mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
if ($diff = array_diff_key($variables, $mergedParams)) {throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));}
$url ='';
$optional = true;
at UrlGenerator ->doGenerate (array('titreOuvrage'), array('_controller' => 'SBMainBundleControllerMainController::ouvrageAction'), array(), array(array('variable', '/', '[^/]++', 'titreOuvrage'), array('text', '/ouvrage')), array(), 'sb_main_ouvrage', '1', array(), array())
in appcachedevappDevDebugProjectContainerUrlGenerator.php at line 92 +
at appDevDebugProjectContainerUrlGenerator ->generate ('sb_main_ouvrage', array(), '1')
in appcachedevclasses.php at line 1286 +
at Router ->generate ('sb_main_ouvrage', array(), '1')
in vendorsymfonysymfonysrcSymfonyBundleFrameworkBundleControllerController.php at line 52 +
at Controller ->generateUrl ('sb_main_ouvrage')
in srcSBMainBundleControllerMainController.php at line 49 +
at MainController ->indexAction (object(Request))
at call_user_func_array (array(object(MainController), 'indexAction'), array(object(Request)))
in vendorsymfonysymfonysrcSymfonyComponentHttpKernelHttpKernel.php at line 144 +
at HttpKernel ->handleRaw (object(Request), '1')
in vendorsymfonysymfonysrcSymfonyComponentHttpKernelHttpKernel.php at line 64 +
at HttpKernel ->handle (object(Request), '1', true)
in vendorsymfonysymfonysrcSymfonyComponentHttpKernelDependencyInjectionContainerAwareHttpKernel.php at line 69 +
at ContainerAwareHttpKernel ->handle (object(Request), '1', true)
in vendorsymfonysymfonysrcSymfonyComponentHttpKernelKernel.php at line 185 +
at Kernel ->handle (object(Request))
in webapp_dev.php at line 28
我的地图页面控制器:
public function ouvrageAction(Ouvrages $ouvrages){
$ouvrage = $ouvrages->getTitreOuvrage();
$categories = $this->getDoctrine()->getRepository('SBMainBundle:Categories')->getAllCats();
$ouvragesVentes = $this->getDoctrine()->getRepository('SBMainBundle:Ouvrages')->getOuvragesVentesByName($ouvrage);
$ouvragesEchanges = $this->getDoctrine()->getRepository('SBMainBundle:Ouvrages')->getOuvragesEchangesByName($ouvrage);
$datas = array('ouvragesVentes'=>$ouvragesVentes,'ouvragesEchanges'=>$ouvragesEchanges,'categories'=>$categories,'ouvrages'=>$ouvrages);
return $this->render('SBMainBundle:Main:ouvrage.html.twig',$datas);
}
您的表单没有实体(或多个),这意味着您的$form->getData()将返回一个数组。而且,正如错误所说,您不能将数组传递给persist()方法。
如果您的目标是保存数据库中发送的每个搜索,则需要创建一个实体SearchBox(或您想称之为的任何名称),并相应地设置data_class。
如果您不想存储搜索,那么就不需要调用处理程序。(因为它除了调用persist()之外什么都不做)而且您不需要实体,请检查如何在没有data_class 的情况下处理提交
Btw。在处理程序中,您调用$form->isValid()而不调用$form->isSubmitted(),并且此代码为
if ($formHandler->process()){
return $this->redirect($this->generateUrl(''));
}
if ($form->isSubmitted() && $form->isValid()) {
// You will never come here, because $formHandler->process() will return true if your form is valid, and leave your indexAction
}
希望它能帮助你。
编辑
您传递到存储库的数据是
$searchBoxValue = $form->getData();
这将返回标记searchBoxValue
作为一个数组,因为您需要所有的表单数据。
但你想要的是获得特定的搜索字段数据,你需要做
$searchBoxValue = $form->get('searchBox')->getData();
请注意,我建议使用queryBuilder,或者至少保护您的查询不受sql注入的影响。
例如
public function getOuvrageName($titre){
$query = $this->getEntityManager()->createQuery(
"SELECT o FROM SBMainBundle:Ouvrages o WHERE o.titreOuvrage = :titre ORDER BY o.id DESC "
)
->setParameter('titre', $titre);
return $query->getResult();
}