简体   繁体   中英

How can I define an undefined method named “handleRequest” of class in Symfony 4?

use Symfony\Component\Form\Forms;

public function form($slug, Request $request){
  $id = $request->request->get('id');
  $EntityName = 'App\\Entity\\' . ucwords($slug);
  $item = new $EntityName();
  $item= $this->getDoctrine()->getRepository($EntityName)->find($id);
  $form = $this->createFormBuilder($item);

  foreach ($classes->fieldMappings as $fieldMapping) {
    $form = $form->add($fieldMapping['fieldName'], TextType::class, array('attr' => array('class' => 'form-control')));
  }
  $form->add('cancel', ButtonType::class, array('label' => 'Abbrechen','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar close_h')))
  ->add('save', SubmitType::class, array('label' => 'Speichern','attr' => array('id' => 'submit-my-beautiful-form','class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')))
  ->getForm();

  $form->handleRequest($request);
}

Attempted to call an undefined method named "handleRequest" of class "Symfony\\Component\\Form\\FormBuilder".

You're calling the method on the wrong object here. Note that you're calling $this->createFormBuilder() which returns a FormBuilder , not a form.

What I would suggest is name the variable like this:

$formBuilder = $this->createFormBuilder($item);

And then, you're not storing the result of the getForm() call on the form builder. You should do this:

foreach (...) {
  $formBuilder->add(...);
}

$formBuilder
  ->add(...)
  ->add(...)

$form = $formBuilder->getForm();

...and this way you'll get an instance of Form which has the handleRequest() method, and the call to it will produce the result you're expecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM