У меня возникли проблемы с внедрением контроллера, создающего форму, в которую можно загружать файлы. Когда контроллер отображается в определенных частях файла ветки, я получаю эту ошибку:
An exception has been thrown during the rendering of a template ("Expected argument of type "Symfony\Component\HttpFoundation\File\UploadedFile", "string" given").
Это странно, так как в других частях того же веточного файла ожидаемый аргумент передается без проблем. Проблема, похоже, заключается в другой форме в том же файле ветки, которая плохо работает с моей формой встроенного контроллера.
Часть, которая, кажется, вызывает проблему:
<div id = "payment_checkout_form">
{% if cId and shippingRegionId %}
{% set savedPath =path('cart_set_shipping', {'store_id': webstore.id, 'shippingRegion': shippingRegionId,'cId':cId}) %}
{{ form_start(form, {'attr': {'id': 'form_checkout','data-url':savedPath}}) }}
{% else %}
{{ form_start(form, {'attr': {'id': 'form_checkout'}}) }}
{% endif %}
{{ render(url('passport')) }}
Соответствующая часть моего PassportType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', 'file', array('label' => false) , [
'multiple' => true,
'label' => '',
'attr' => [
'accept' => 'image/*',
'multiple' => 'multiple'
]
]
)
->add('confirm', 'submit');
}
public function configureOptions(OptionsResolver $resolver){
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Passport',
));
}
Соответствующая часть моего паспорта:
/**
* @Assert\File(maxSize = "6000000")
*/
private $file;
/**
* Sets file.
*
* @param Symfony\Component\HttpFoundation\File\UploadedFile $file
*/
public function setFile(UploadedFile $file = null) {
$this->file = $file;
}
Соответствующая часть моего контроллера Passport
/**
* @Route("/passport", name = "passport")
*/
public function createPassportAction(Request $request)
{
$request = $this->get('request_stack')->getMasterRequest();
$passport = new Passport();
$passport->setName('default');
$form = $this->createForm(new PassportType(), $passport);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$files = $request->files->get('passportPhoto');
if (!empty($files)) {
$this->uploadFile($files);
}
}
return $this->render('passport.html.twig', [
'form' => $form->createView(),
'isFormSubmitted' => $form->isSubmitted(),
'passportImages' => $this->getDoctrine()->getRepository('AppBundle\Entity\Passport')->findAll(),
]);
}
{{ render(url('passport')) }} is the embedded controller that renders the file upload form. If I put the{{ render(url('passport')) }} над form_start другой формы все работает.




Отвечая на мой собственный вопрос:
встраивание формы в другую форму, как я пытаюсь сделать в вопросе, с помощью рендеринга невозможно. Я исправил свою проблему, сначала удалив вызов рендеринга моей встроенной формы паспорта и сделав мой тип паспорта подтипом типа, который используется в форме проверки, например:
public function buildForm(FormBuilderInterface $builder, array $options){
$builder
...
->add('passport', new PassportType(), array(
'required' => true
))
...
}
Я все еще хотел, чтобы контроллер паспортной части моей формы находился в своем собственном файле. Для этого я вызвал свой паспортный контроллер внутри кассового контроллера, используя прямой метод, например:
$files = $request->files->get('order')['passport_id'];
$store_id = $request->attributes->get('store_id');
$this->forward('AppBundle\Controller\PassportController::uploadFile',
[ 'files' => $files, 'store_id' => $store_id ]);