以 symfony 形式上传图片

Upload image in symfony form

我遇到了一个奇怪的问题。我在表单中添加了上传图片字段。当我在 twig 文件中使用这段代码时,一切正常

{{ form_start(form) }}
<button>d</button>
{{ form_end(form) }}

但是当我想使用 form_widget 来装饰表单的外观时,当我尝试提交表单时会出现此错误

FatalErrorException Error: Call to a member function getFileName() on string.

这是导致问题的视图

{% extends 'BridgeTravelBundle:Admin:layout.html.twig' %}

{% block body %}
    <div class="col-md-12 col-sm-12 col-xs-12">
        <div class="x_panel">
            <form method="POST" id="demo-form2" data-parsley-validate class="form-horizontal form-label-left">
                <div class="form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12">Nom</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                        {{ form_widget(form.name, { 'attr': {'class': 'form-control', 'placeholder': 'Prenom' } }) }}
                        {{ form_errors(form.name) }}
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12">Icon</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                        {{ form_widget(form.icon, { 'attr': {'class': 'form-control', 'placeholder': 'Prenom' } }) }}
                        {{ form_errors(form.icon) }}
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12">Icon</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                        {{ form_widget(form.file) }}
                        {{ form_errors(form.file) }}
                    </div>
                </div>

                <div class="ln_solid"></div>
                <div class="form-group">
                    <div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
                        <button class="btn btn-success">Valider</button>
                    </div>
                </div>

            </form>
        </div>
    </div>
{% endblock body %}

这是控制表单的动作。

public function addCategoryAction(Request $request){

        $category=new Category();
        $form=$this->createForm(CategoryType::class,$category);
        $form->handleRequest($request);

        if ($form->isSubmitted())
        {
            $image= $form['file']->getData();
            $em=$this->getDoctrine()->getManager();
            $req = $request->request->get('Bridge_TravelBundle_Category');
            $category->setName($req['name']);
            $category->setIcon($req['icon']);
            $name = $req['name'];
            try {
                if(!is_dir("CategoriesPictures")){
                    mkdir("CategoriesPictures");
                }

                move_uploaded_file($image,"CategoriesPictures/".$image->getFileName());
                rename("CategoriesPictures/".$image->getFileName() , "CategoriesPictures/".$name.".jpg");

            }
            catch (IOExceptionInterface $e) {
                echo "Erreur Profil existant ou erreur upload image ".$e->getPath();
            }

            $em->persist($category);
            $em->flush();
            return $this->redirectToRoute('admin_categories');
        }

        return $this->render("BridgeTravelBundle:Admin:addcategory.html.twig",array('form' => $form->createView(),));
    }

这个CategoryType.php

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CategoryType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name')
            ->add('icon')
            ->add('file',FileType::class, array(
                    'multiple'    => false,
                    'attr' => array(

                        'accept' => 'image/*',
                    )
                )
            )       ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Bridge\TravelBundle\Entity\Category'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'Bridge_TravelBundle_Category';
    }
}

您的 form 标签中缺少此属性 enctype='multipart/form-data'

您应该 form_start & form_end 而不是自己编写 form 标签。

您也可以像这样使用 form_start 函数放置自定义属性

{{ form_start(form, { 'attr': {'class': 'foo', 'id': 'bar' } }) }} 

此外,form_end 非常重要,因为它还会打印出 form_rest 和任何缺失的字段。

<form method="POST" id="demo-form2" data-parsley-validate class="form-horizontal form-label-left">

会变成

{{ form_start(form, { 'attr': { 'id': 'demo-form2', 'data-parsley-validate': null, 'class': 'form-horizontal form-label-left' } }) }}

</form>

会变成

{{ form_end(form) }}