数据库中的映像_名称始终为空vichuploaderbundle symfony2

数据库中的映像_名称始终为空vichuploaderbundle symfony2,symfony,doctrine-orm,vichuploaderbundle,image-file,Symfony,Doctrine Orm,Vichuploaderbundle,Image File,我正在尝试使用图像文件添加新用户。我正在使用和。因此,创建了新用户,但image_name始终为空 这是我的图像实体: namespace SocialNetworkBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Gedmo\Mapping\Annotation as Gedmo; use Vich\UploaderBundle\

我正在尝试使用图像文件添加新用户。我正在使用和。因此,创建了新用户,但image_name始终为空

这是我的图像实体:

namespace SocialNetworkBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\File;

/**
 * Image
 *
 * @ORM\Table(name="image")
 * @ORM\Entity(repositoryClass="SocialNetworkBundle\Repository\ImageRepository")
 * @Vich\Uploadable 
 */
class Image {

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * Get id
     *
     * @return int
     */
    public function getId() {
        return $this->id;
    }

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     * 
     * @Vich\UploadableField(mapping="image", fileNameProperty="imageName")
     * @Assert\File(
     *     maxSize = "1024k",
     *     mimeTypes = {"image/png", "image/jpeg", "image/jpg"},
     *     mimeTypesMessage = "Please upload a valid PDF or valid IMAGE"
     * )
     * 
     * @var File
     */
    private $imageFile;

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

    /**
     * @ORM\Column(type="datetime")
     *
     * @var \DateTime
     */
    private $updatedAt;

    /**
     * Set imageName
     *
     * @param string $imageName
     *
     * @return Image
     */
    public function setImageName($imageName) {
        $this->imageName = $imageName;

        return $this;
    }

    /**
     * Get imageName
     *
     * @return string
     */
    public function getImageName() {
        return $this->imageName;
    }

    /**
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
     *
     * @return Image
     */
    public function setImageFile(File $image = null) {
        $this->imageFile = $image;

        if ($image) {
            $this->updatedAt = new \DateTime('now');
        }

        return $this;
    }

    /**
     * @return File|null
     */
    public function getImageFile() {
        return $this->imageFile;
    }

}
用户实体:

namespace UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\File;    
use SocialNetworkBundle\Entity\Image ;

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="UserBundle\Repository\UserRepository") 
 * @Vich\Uploadable
 */
class User extends BaseUser 
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, unique=false)
     * @Assert\Length(min=2, max=100)
     */
    private $name;

    /**
     * @ORM\OneToOne(targetEntity="SocialNetworkBundle\Entity\Image", cascade={"persist", "merge", "remove"})
     * @ORM\JoinColumn(name="image_id", referencedColumnName="id")
     * @Assert\Valid()
     */
    private $image;

    /**
     * Set name
     *
     * @param string $name
     *
     * @return User
     */
    public function setName($name) 
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName() 
    {
        return $this->name;
    }

    /**
     * Set image
     *
     * @param \SocialNetworkBundle\Entity\Image $image
     *
     * @return User
     */
    public function setImage(\SocialNetworkBundle\Entity\Image $image = null) 
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return \SocialNetworkBundle\Entity\Image
     */
    public function getImage() 
    {
        return $this->image;
    }
}
图像类型:

namespace SocialNetworkBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Vich\UploaderBundle\Form\Type\VichFileType;

class ImageType extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder
     ->add('imageFile', VichFileType::class, array(
                    'required'      => false,
                    'allow_delete'  => true, // not mandatory, default is true
                    'download_link' => true, // not mandatory, default is true
                    ))

    ;
  }

  public function setDefaultOptions(OptionsResolverInterface $resolver)
  {
    $resolver->setDefaults(array(
        'data_class' => 'SocialNetworkBundle\Entity\Image',
    ));
  }

  public function getName()
  {
    return 'socialnetworkbundle_image';
  }
}
注册表格:

namespace UserBundle\Form\Type;

use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
use SocialNetworkBundle\Form\ImageType;

class RegistrationFormType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        // add your custom field
        $builder->add('name')
            ->add('roles', 'collection', array(
                'type'    => 'choice',
                'options' => array(
                    'choices' => array(
                        'ROLE_ADMIN' => 'Admin',
                    ),
                ),
             ))
             ->add('image', new ImageType())
         ;
    }

    public function getName()
    {
        return 'user_registration';
    }
}
和register.html.twig

{% extends "UserBundle::layout.html.twig" %}


{% block body %}
    <center> <h1> Inscription </h1> </center>
    <aside class="col-sm-3">
        <div class="panel panel-default">
            <div class="panel-heading">Inscription</div>
            <div class="panel-body">
                Veuillez remplir les champs 
            </div>
        </div>
    </aside>

    <!--timeline-->
    <section class="timeline col-sm-9">
        <!--post Timeline-->
        <div class="thumbnail thumbnail-post">
            <!--caption-->
            <div class="caption">
                <form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST" class="form-horizontal">
                    <div class="form-group">    
                        {{ form_errors(form.name) }}    
                        <div class="col-sm-9">
                            Nom   {{ form_widget(form.name,  { 'attr': {'class': 'form-control', 'placeholder': 'form.name'|trans } })}}
                        </div>
                    </div>

                    <div class="form-group">    
                        {{ form_errors(form.email) }}
                        <div class="col-sm-9">
                            Email   {{ form_widget(form.email, { 'attr': {'class': 'form-control', 'placeholder': 'form.email'|trans } }) }}
                        </div>
                    </div>
                    <div class="form-group">
                        {{ form_errors(form.username) }}
                        <div class="col-sm-9">
                            Pseudo   {{ form_widget(form.username, { 'attr': {'class': 'form-control', 'placeholder': 'form.username'|trans } }) }}
                        </div>
                    </div>    
                    <div class="form-group">
                        {{ form_errors(form.plainPassword.first) }} 
                        <div class="col-sm-9">    
                            Mot de passe    {{ form_widget(form.plainPassword.first, { 'attr': {'class': 'form-control', 'placeholder': 'form.password'|trans } }) }}
                        </div>
                    </div>

                    <div class="form-group">
                        {{ form_errors(form.plainPassword.second) }}
                        <div class="col-sm-9">  
                            Confirmer le mot de passe    {{ form_widget(form.plainPassword.second, { 'attr': {'class': 'form-control', 'placeholder': 'form.password_confirmation'|trans } }) }}
                        </div>
                    </div>

                    <div class="form-group">
                        {# Génération du label. #}
                        {{ form_label(form.image.imageFile, "Image", {'label_attr': {'class': 'col-sm-3 control-label'}}) }}

                        {# Affichage des erreurs pour ce champ précis. #}
                        {{ form_errors(form.image.imageFile) }}

                        <div class="col-sm-4">
                            {# Génération de l'input. #}
                            {{ form_widget(form.image.imageFile, {'attr': {'class': 'form-control'}}) }} 
                        </div>
                    </div>
                    <br />

                    <div id="roles">
                        <div class="form-group">
                            <div class="col-sm-4">   {{ form_widget(form.roles, { 'attr': {'class': 'form-control', 'placeholder': 'form.role'|trans } }) }}
                            </div>
                            {{ form_errors(form.roles) }}
                        </div>
                    </div>
                    {{ form_rest(form) }}

                    <div class="form-group">
                        <div class="col-md-4 col-sm-4 col-xs-12 col-md-offset-3">
                            <input class="btn btn-default submit" type="submit" value="{{ 'registration.submit'|trans }}">
                        </div>
                    </div>
                </form>
            </div> <!--#caption-->

            <!--#post timeline-->
        </div>
        <!--#timeline-->
    </section>
{% endblock %}

{% block js %}
    <script>
        $(document).ready(function () {
            $('#roles').hide();
        });
    </script>
{% endblock %} 

在我的数据库中,列image\u name处有一个空值。如何解决此问题?

您应该在图像实体中添加一个映射字段(例如updatedAt)。使用方法setImageFile设置映像时,还应更新映射字段以触发事件侦听器并处理上载的文件

namespace SocialNetworkBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\File;

/**
 * Image
 *
 * @ORM\Table(name="image")
 * @ORM\Entity(repositoryClass="SocialNetworkBundle\Repository\ImageRepository")
 * @Vich\Uploadable 
 */
class Image 
{    
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * Get id
     *
     * @return int
     */
    public function getId() 
    {
        return $this->id;
    }

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     * 
     * @Vich\UploadableField(mapping="image", fileNameProperty="imageName")
     * @Assert\File(
     *     maxSize = "1024k",
     *     mimeTypes = {"image/png", "image/jpeg", "image/jpg"},
     *     mimeTypesMessage = "Please upload a valid PDF or valid IMAGE"
     * )
     * 
     * @var File
     */
    private $imageFile;

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

    /**
     * @ORM\Column(type="datetime")
     *
     * @var \DateTime
     */
    private $updatedAt;

    /**
     * Set imageName
     *
     * @param string $imageName
     *
     * @return Image
     */
    public function setImageName($imageName)
    {
        $this->imageName = $imageName;

        return $this;
    }

    /**
     * Get imageName
     *
     * @return string
     */
    public function getImageName()
    {
        return $this->imageName;
    }

    /**
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
     *
     * @return Image
     */
    public function setImageFile(File $image = null) 
    {
        $this->imageFile = $image;

        if ($image) {
            $this->updatedAt = new \DateTime('now');
        }

        return $this;
    }

    /**
     * @return File|null
     */
    public function getImageFile() 
    {
        return $this->imageFile;
    }
}

image_name仍然获得空值请确保在更改代码后更新了架构(“应用/控制台原则:架构:更新-强制”或使用迁移)并清除了应用程序缓存。对于corse,但它仍然获得空值OK,让我们再次检查。您已将updatedAt字段添加到Image类中,并使用if($Image){$this->updatedAt=new\DateTime('now');}修改了setImageFile方法。对吗?另外,请检查您是否在config.yml中设置了上载映射。如果可能,请使用config.yml文件中的映射设置更新您的问题。只需将config.yml中的映射名称和图像实体更改为一些中性名称,如“图像”。但在这种情况下,所有图像(用于所有相关实体)都将上载到一个存储器中。如果您想为各种实体分离目录,只需删除图像实体并将vichuploader字段添加到实体中,并对eacn实体使用单独的映射即可。
namespace SocialNetworkBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\File;

/**
 * Image
 *
 * @ORM\Table(name="image")
 * @ORM\Entity(repositoryClass="SocialNetworkBundle\Repository\ImageRepository")
 * @Vich\Uploadable 
 */
class Image 
{    
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * Get id
     *
     * @return int
     */
    public function getId() 
    {
        return $this->id;
    }

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     * 
     * @Vich\UploadableField(mapping="image", fileNameProperty="imageName")
     * @Assert\File(
     *     maxSize = "1024k",
     *     mimeTypes = {"image/png", "image/jpeg", "image/jpg"},
     *     mimeTypesMessage = "Please upload a valid PDF or valid IMAGE"
     * )
     * 
     * @var File
     */
    private $imageFile;

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

    /**
     * @ORM\Column(type="datetime")
     *
     * @var \DateTime
     */
    private $updatedAt;

    /**
     * Set imageName
     *
     * @param string $imageName
     *
     * @return Image
     */
    public function setImageName($imageName)
    {
        $this->imageName = $imageName;

        return $this;
    }

    /**
     * Get imageName
     *
     * @return string
     */
    public function getImageName()
    {
        return $this->imageName;
    }

    /**
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
     *
     * @return Image
     */
    public function setImageFile(File $image = null) 
    {
        $this->imageFile = $image;

        if ($image) {
            $this->updatedAt = new \DateTime('now');
        }

        return $this;
    }

    /**
     * @return File|null
     */
    public function getImageFile() 
    {
        return $this->imageFile;
    }
}