Symfony2 FOSUserBundle不会上传个人资料图片

时间:2015-12-28 22:58:37

标签: php symfony fosuserbundle

我正在使用symphony 3和FOSUserBundle创建一个应用程序 我用其他礼物创建了我的User类,其中一个是个人资料图片 这是我的用户类:

#src/UserBundle/Entity/User.php
<?php
namespace UserBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 * @ORM\HasLifecycleCallbacks()
 */
class User extends BaseUser {
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(name="first_name", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $first_name;

    /**
     * @var string
     * @ORM\Column(name="last_name", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $last_name;

    /**
     * @var string
     * @ORM\Column(name="address", type="string", length=255, nullable=true)
     */
    private $address;

    /**
     * @var string
     * @ORM\Column(name="post", type="string", length=255, nullable=true)
     */
    private $post;

    /**
     * @var string
     * @ORM\Column(name="city", type="string", length=255, nullable=true)
     */
    private $city;

    /**
     * @var \DateTime
     * @ORM\Column(name="birth_date", type="datetime", nullable=true)
     */
    private $birth_date;

    /**
     * @var string
     * @ORM\Column(name="gender", type="string", length=1)
     */
    private $gender;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $path;

    /**
     * @Assert\File(
     *      maxSize = "5M",
     *      mimeTypes = {"image/jpeg", "image/gif", "image/png", "image/tiff"},
     *      maxSizeMessage = "The maximum allowed file size is 5MB.",
     *      mimeTypesMessage = "Only the file types image are allowed.")
     */
    public $file;

    public function __construct() {
        parent::__construct();
    }

    /**
     * @return string
     */
    public function getAddress() {
        return $this->address;
    }

    /**
     * @return string
     */
    public function getFirstName() {
        return $this->first_name;
    }

    /**
     * @param string $first_name
     */
    public function setFirstName($first_name) {
        $this->first_name = $first_name;
    }

    /**
     * @return string
     */
    public function getLastName() {
        return $this->last_name;
    }

    /**
     * @param string $last_name
     */
    public function setLastName($last_name) {
        $this->last_name = $last_name;
    }

    /**
     * @param string $address
     */
    public function setAddress($address) {
        $this->address = $address;
    }

    /**
     * @return string
     */
    public function getPost() {
        return $this->post;
    }

    /**
     * @param string $post
     */
    public function setPost($post) {
        $this->post = $post;
    }

    /**
     * @return string
     */
    public function getCity() {
        return $this->city;
    }

    /**
     * @param string $city
     */
    public function setCity($city) {
        $this->city = $city;
    }

    /**
     * @return \DateTime
     */
    public function getBirthDate() {
        return $this->birth_date;
    }

    /**
     * @param \DateTime $birth_date
     */
    public function setBirthDate($birth_date) {
        $this->birth_date = $birth_date;
    }

    /**
     * @return string
     */
    public function getGender() {
        return $this->gender;
    }

    /**
     * @param string $gender
     */
    public function setGender($gender) {
        $this->gender = $gender;
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload() {
        if (null !== $this->file) {
            $this->path = uniqid('', true) . '.' . $this->file->guessExtension();
        }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload() {
        if (null === $this->file) {
            return;
        }
        $this->file->move($this->getUploadRootDir(), $this->path);
        unset($this->file);
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeUpload() {
        if ($this->file == $this->getAbsolutePath()) {
            unlink($this->file);
        }
    }

    public function getAbsolutePath() {
        return null === $this->path ? null : $this->getUploadRootDir() . '/' . $this->path;
    }

    public function getWebPath(){
        return null === $this->path ? null : $this->getUploadDir() . '/' . $this->id . '/' . $this->path;
    }

    protected function getUploadRootDir() {
        return __DIR__ . '/../../../web/' . $this->getUploadDir() . '/' . $this->id;
    }

    protected function getUploadDir() {
        return 'uploads/users';
    }

    /**
     * @param string $path
     * @return User
     */
    public function setPath($path) {
        $this->path = $path;
        return $this;
    }

    /**
     * @return string
     */
    public function getPath() {
        return $this->path;
    }

    public function setEmail($email) {
        $email = is_null($email) ? '' : $email;
        parent::setEmail($email);
        $this->setUsername($email);

        return $this;
    }
}

然后我有了ProfileFormType类:

#src/UserBundle/Form/Type/ProfileFormType.php
<?php

namespace UserBundle\Form\Type;

use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ProfileFormType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->remove('username');
        $builder->remove('current_password');
        $builder->add('first_name', TextType::class, array('label' => "First Name", 'invalid_message' => 'Please enter your First Name'));
        $builder->add('last_name', TextType::class, array('label' => "Last Name", 'invalid_message' => 'Please enter your Last Name'));
        $builder->add('address', TextType::class);
        $builder->add('post', TextType::class, array('label' => "Post Code"));
        $builder->add('city', TextType::class);
        $builder->add('gender', ChoiceType::class, array('choices' => array('Male' => 'm', 'Female' => 'f'), 'choices_as_values' => true));
        $builder->add('birth_date', DateType::class, array('label' => "Birth Date", 'widget' => 'single_text', 'invalid_message' => 'Please enter a valid date'));
        $builder->add('file', FileType::class, array('label' => "Profile Picture", 'data_class' => null));
    }

    public function getParent() {
        return 'FOS\UserBundle\Form\Type\ProfileFormType';
    }
}

我的表单看起来像:

#src/UserBundle/Resources/views/Profile/edit_content.html.twig
        {{ form_start(form, { 'action': path('fos_user_profile_edit'), 'attr': { 'class': 'fos_user_profile_edit' } }) }}
        <div class="col-md-12">
            <span class="btn btn-default btn-file"> Browse {{ form_widget(form.file) }}</span>
        </div>
        <div class="col-md-12">
            <input type="submit" id="_submit" name="_submit" value="{{ 'profile.edit.submit'|trans }}" class="btn btn-success" />
        </div>
        {{ form_end(form) }}

表单已正确提交,如果存在错误则显示错误。
但是在数据库中,'path'为空,文件夹(具有读/写权限)为空 当我在表单中添加{{ form_enctype(form) }}时出现错误:Unknown "form_enctype" function in FOSUserBundle:Profile:edit_content.html.twig
我的问题是:我该如何解决这个问题?
我看不出任何错误,一切看起来都不错,但它不起作用。

1 个答案:

答案 0 :(得分:1)

您需要为实体启用生命周期回调:http://symfony.com/doc/current/book/doctrine.html#lifecycle-callbacks

相关问题