Symfony4 / Twig / AbstractTypeExtension:无法覆盖文件小部件以显示存储在实体和数据库中的图片

时间:2018-07-13 18:50:27

标签: symfony twig containers symfony-forms symfony4

我有一个“成员”实体,内部有个人资料图片(不是图像的路径),存储在mysql数据库中。

当我在index动作和show动作中显示图片时,它可以工作,但是当我要对其进行编辑时,我想显示存储的当前图片,就像处理其他实体数据一样。

我在Symfony文档:https://symfony.com/doc/current/form/create_form_type_extension.html中遵循了howto,但是它不起作用。

也尝试了以下解决方案:Symfony/Twig: how to pass additional data to a form?

我包含代码:

src / Entity / Member.php

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * Member
 *
 * @ORM\Table(name="members", uniqueConstraints={@ORM\UniqueConstraint(name="ix_first_name_last_name", columns={"first_name","last_name"})})
 * @ORM\Entity(repositoryClass="App\Repository\MemberRepository")
 * @UniqueEntity(fields="email", message="Email already taken")
 * @UniqueEntity(fields="username", message="Username already taken")
 * @ORM\HasLifecycleCallbacks()
 */
class Member implements UserInterface, \Serializable
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $firstName;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $lastName;

    /**
     * @ORM\Column(type="blob", nullable=true)
     */
    private $pictureProfile;

    /**
     * @ORM\Column(type="string", length=255, unique=true)
     * @Assert\NotBlank()
     * @Assert\Email()
     */
    private $email;


    public function getId()
    {
        return $this->id;
    }

    public function getFirstName(): ?string
    {
        return $this->firstName;
    }

    public function setFirstName(string $firstName): self
    {
        $this->firstName = $firstName;

        return $this;
    }

    public function getLastName(): ?string
    {
        return $this->lastName;
    }

    public function setLastName(string $lastName): self
    {
        $this->lastName = $lastName;

        return $this;
    }

    public function getPictureProfile()
    {
        if ($this->pictureProfile != null) {
            $image = base64_encode(stream_get_contents($this->pictureProfile));
        } else {
            $image = null;
        }
        return $image;
    }

    public function setPictureProfile($pictureProfile): self
    {
        $this->pictureProfile = $pictureProfile;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(?string $email): self
    {
        $this->email = $email;

        return $this;
    }

}

src / Controller / MemberController.php

<?php

namespace App\Controller;

use App\Entity\Member;
use App\Form\MemberType;
use App\Repository\MemberRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * @Route("/member")
 */
class MemberController extends Controller
{

    /**
     * @Route("/", name="member_index", methods="GET")
     */
    public function index(MemberRepository $memberRepository): Response
    {
        return $this->render('member/index.html.twig', ['members' => $memberRepository->findAll()]);
    }

    /**
     * @Route("/new", name="member_new", methods="GET|POST")
     */
    public function new(Request $request, UserPasswordEncoderInterface $passwordEncoder): Response
    {
        $member = new Member();
        $form = $this->createForm(MemberType::class, $member);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            if ($_FILES['member']['size']['pictureProfile'] > 0) {
                $image = fread(fopen($_FILES['member']['tmp_name']['pictureProfile'], 'r'), filesize($_FILES['member']['tmp_name']['pictureProfile']));
                $member->setPictureProfile($image);
            }

            $em = $this->getDoctrine()->getManager();
            $em->persist($member);
            $em->flush();

            return $this->redirectToRoute('member_index');
        }

        return $this->render('member/new.html.twig', [
            'member' => $member,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="member_show", methods="GET")
     */
    public function show(Member $member): Response
    {
        return $this->render('member/show.html.twig', ['member' => $member]);
    }

    /**
     * @Route("/{id}/edit", name="member_edit", methods="GET|POST")
     */
    public function edit(Request $request, Member $member, UserPasswordEncoderInterface $passwordEncoder): Response
    {
        $form = $this->createForm(MemberType::class, $member);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if ($_FILES['member']['size']['pictureProfile'] > 0) {
                $image = fread(fopen($_FILES['member']['tmp_name']['pictureProfile'], 'r'), filesize($_FILES['member']['tmp_name']['pictureProfile']));

                $member->setPictureProfile($image);
            }

            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('member_index');
        }

        return $this->render('member/edit.html.twig', [
            'member' => $member,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="member_delete", methods="DELETE")
     */
    public function delete(Request $request, Member $member): Response
    {
        if ($this->isCsrfTokenValid('delete' . $member->getId(), $request->request->get('_token'))) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($member);
            $em->flush();
        }

        return $this->redirectToRoute('member_index');
    }
}

src / Form / MemberType.php

<?php

namespace App\Form;
use App\Entity\Member;
use App\Entity\ResearchProject;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class MemberType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName', TextType::class, array('attr' => array('class' => 'form-control')))
            ->add('lastName', TextType::class, array('attr' => array('class' => 'form-control')))
            ->add('pictureProfile', FileType::class, array(
                'data_class' => null,
                'attr' => array('class' => 'form-control'),
                'image_property' => 'pictureProfile'))
            ->add('email', EmailType::class, array('attr' => array('class' => 'form-control')))
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Member::class,
        ]);
    }
}

src / Form / Extension / ImageTypeExtension.php

<?php

namespace App\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\FileType;

class ImageTypeExtension extends AbstractTypeExtension
{
    public function getExtendedType()
    {
        return FileType::class;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
// makes it legal for FileType fields to have an image_property option
        $resolver->setDefined(array('image_property'));
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        if (isset($options['image_property'])) {
// this will be whatever class/entity is bound to your form (e.g. Media)
            $parentData = $form->getParent()->getData();

            $imageData = null;
            if (null !== $parentData) {
                $accessor = PropertyAccess::createPropertyAccessor();
                $imageData = $accessor->getValue($parentData, $options['image_property']);
            }
            else{
                $imageData = "Didn't load anything";
            }

// sets an "image_data" variable that will be available when rendering this field
            $view->vars['image_data'] = $imageData;
        }
    }

}

src / templates / form / fields.html.twig

{% extends 'form_div_layout.html.twig' %}

{% block file_widget %}
    {% spaceless %}

        {{ block('form_widget') }}
        {% if image_data is not null %}
            <img height="80" alt="No Image" src="data:image/png;base64,{{ image_data }}" class="img img-responsive img-preview thumbnail"/>
        {% endif %}

    {% endspaceless %}
{% endblock %}

src / templates / member / edit.html.twig

{% extends 'base.html.twig' %}

{% block title %}Edit Member{% endblock %}

{% block body %}
    <h1>Edit Member</h1>

    {{ include('member/_form.html.twig', {'button_label': 'Update'}) }}
    {{ include('member/_delete_form.html.twig') }}
    <a class="btn btn-secondary" href="{{ path('member_index') }}">Back to list</a>
{% endblock %}

src / templates / member / _form.html.twig

{% form_theme form 'form/fields.html.twig' %}

{{ form_start(form, {'attr': {'novalidate': 'novalidate'}}) }}
    {{ form_widget(form) }}
    <button class="btn btn-primary">{{ button_label|default('Save') }}</button>
{{ form_end(form) }}

src / templates / member / index.html.twig

{% extends 'base.html.twig' %}

{% block title %}Member index{% endblock %}

{% block body %}
    <h1>Member index</h1>

    <table class="table table-hover">
        <thead>
            <tr>
                <!-- <th scope="col">Id</th> -->
                <th scope="col">First Name</th>
                <th scope="col">Last Name</th>
                <th scope="col">Picture Profile</th>
                <th>Email</th>
                <th scope="col">Actions</th>
            </tr>
        </thead>
        <tbody>
        {% for key, member in members %}
            <tr>
                <td>{{ member.firstName }}</td>
                <td>{{ member.lastName }}</td>
                <td><img height="80" alt="No Image" src="data:image/png;base64,{{ member.pictureProfile }}" class="img img-responsive img-preview thumbnail"/></td>
                <td>{{ member.email }}</td>
                <td>
                    <a href="{{ path('member_show', {'id': member.id}) }}">show</a>
                    <a href="{{ path('member_edit', {'id': member.id}) }}">edit</a>
                </td>
            </tr>
        {% else %}
            <tr>
                <td colspan="29">no records found</td>
            </tr>
        {% endfor %}
        </tbody>
    </table>

    <a href="{{ path('member_new') }}">Create new</a>
{% endblock %}

config / services.yaml

services:
    # ...

    App\Form\Extension\ImageTypeExtension:
        tags:
            - { name: form.type_extension, extended_type: Symfony\Component\Form\Extension\Core\Type\FileType }

所有这些代码之后,由于以下这一行,我知道我的问题的关键在MemberType.php中:

->add('pictureProfile', FileType::class, array(
                'data_class' => null,
                'attr' => array('class' => 'form-control'),
                'image_property' => 'pictureProfile'))

我得到了呈现的html(请注意src属性中的内容):

<div>
<label for="member_pictureProfile" class="required">Picture profile</label>
<input id="member_pictureProfile" name="member[pictureProfile]" required="required" class="form-control" type="file">
<img alt="No Image" src="data:image/png;base64," class="img img-responsive img-preview thumbnail" height="80">
</div>

如果我将image_property的值更改为实体的另一个属性,例如firstName,则我已经获得了该属性的值,例如:

->add('pictureProfile', FileType::class, array(
                'data_class' => null,
                'attr' => array('class' => 'form-control'),
                'image_property' => 'firstName'))

我得到了(同样,请注意src属性):

<div>
<label for="member_pictureProfile" class="required">Picture profile</label>
<input id="member_pictureProfile" name="member[pictureProfile]" required="required" class="form-control" type="file">
<img alt="No Image" src="data:image/png;base64,John" class="img img-responsive img-preview thumbnail" height="80">
</div>

这样就可以接收数据了! 为什么它没有收到图像? 只需提一下,我已经在该行中直接尝试了getPictureProfile方法,但是没有用。

非常感谢。

1 个答案:

答案 0 :(得分:0)

没有进行任何测试,就好像您使用了错误的类型扩展名。

您已经麻烦创建了扩展ImageTypeExtension的{​​{1}},但仍在表单配置中使用FileType

FileType

这不是应该的吗?

->add('pictureProfile', FileType::class, array(
                'data_class' => null,
                'attr' => array('class' => 'form-control'),
                'image_property' => 'firstName'))