在编辑时,即使设置了newFile,FileType也为空

时间:2019-06-14 13:05:39

标签: symfony4

即使在开始时设置新文件,编辑时的FileType仍为空。

我尝试将值放入表单中,以在创建表单之前设置文件名,但仍然为空。我使用Symfony4和bootstrap 4。

public function edit(Request $request, ObjectManager $manager, SkillRepository $skillRepo, SkillWantRepository $skillWantRepo)
{
    $skilles = $skillRepo->findAll();
    $skillesWant = $skillWantRepo->findAll();
    //getUser appartient à Symfony, il récupère l'utilisateur connecté
    $user = $this->getUser();
    $skill = new Skill();
    $skillWant = new SkillWant();
    $fileName = $user->getAvatar();
    $user->setAvatar(
        new File($this->getParameter('avatars_directory') . '/' . $user->getAvatar())
    );  
    $form = $this->createForm(AccountType::class, $user);
    $test =$user->getAvatar();

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $file = $form->get('avatar')->getData();
        /** @var Symfony\Component\HttpFoundation\File\UploadedFile $file*/
        $fileName = $this->generateUniqueFileName() . '.' . $file->guessExtension();
        try {
            $file->move(
                $this->getParameter('avatars_directory'),
                $fileName
            );
        } catch (FileException $e) {
            // ... handle exception if something happens during file upload
        }

        //on stocke le nom du fichier dans la db
        // instead of its contents
        $user->setAvatar($fileName);

表格

->add('description', TextareaType:: class, ['required' => false])
->add('avatar', FileType:: class ,['data_class'=>null,'required'=>false, 'label'=>'votre image de profil'])`

我想在下载字段中获取文件,但出现此错误:在属性路径“ avatar”中给出的类型为“字符串”,“ NULL”的预期参数

1 个答案:

答案 0 :(得分:1)

您很近。这很困难,因为'avatar'属性包含字符串文件名或UploadedFile。客户端浏览器,表单验证器和数据库检查属性类型。 https://symfony.com/doc/current/controller/upload_file.html也有一些遗漏,并且没有用于编辑实体的示例控制器代码。试试这个。

  1. 在要上传的Entity属性“ avatar”上添加以下注释: (请参见https://symfony.com/doc/current/reference/constraints/Image.html
/**
 * @ORM\Column(type="string", length=255, nullable=true)
 *
 * @Assert\Type(
 *    type="File",
 *    message="The value {{ value }} is not a valid {{ type }}.")
 * @Assert\Image()
 */
private $avatar;

如果“头像”保存的是非图像文件(例如PDF文件),则注释将为: (请参见https://symfony.com/doc/current/reference/constraints/File.html

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 *
 * @Assert\Type(
 *    type="File",
 *    message="The value {{ value }} is not a valid {{ type }}.")
 * @Assert\File(mimeTypes={ "application/pdf" })
 */
private $avatar;
  1. 在实体文件中,删除由php bin/console make:entity添加的类型提示
public function getAvatar(): ?string
{
    return $this->avatar;
}

应更改为:

public function getAvatar()
{
    return $this->avatar;
}

public function setAvatar(?string $avatar): self
{
    $this->avatar = $avatar;
    return $this;
}

应更改为:

public function setAvatar($avatar): self
{
    $this->avatar = $avatar;
    return $this;
}
  1. Controller new()函数应如下所示: (您需要将出现的User2更改为您的实体名称)
public function new(Request $request): Response
{
    $user2 = new User2();
    $form = $this->createForm(User2Type::class, $user2);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        // $file stores the uploaded picture file.
        /** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
        $file = $user2->getAvatar();
        $filename = null;
        if ($file != null) {
            $filename = $this->generateUniqueFileName().'.'.$file->guessExtension();

            // Move the file to the directory where pictures are stored
            try {
                $file->move(
                    $this->getParameter('avatars_directory'),
                    $filename
                );
            } catch (FileException $e) {
                // ... handle exception if something happens during file upload
            }
        }

        // Updates the avatar property to store the picture file name
        // instead of its contents.
        $user2->setAvatar($filename);

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($user2);
        $entityManager->flush();

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

    return $this->render('user2/new.html.twig', [
        'user2' => $user2,
        'form' => $form->createView(),
    ]);
}
  1. 在Controller edit()函数中,因为化身是可选的,所以代码需要检查空化身。
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;

...

public function edit(Request $request, User2 $user2): Response
{
    $fileName = $user2->getAvatar();
    $oldFileName = $fileName;

    $form = $this->createForm(User2Type::class, $user2);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        /** @var Symfony\Component\HttpFoundation\File\UploadedFile $file*/
        $file = $form->get('avatar')->getData();
        if ($file != null) {
            // The user changed the avatar.
            $fileName = $this->generateUniqueFileName() . '.' . $file->guessExtension();
            try {
                $file->move(
                    $this->getParameter('avatars_directory'),
                    $fileName
                );
                // Delete the old file, if any.
                if ($oldFileName != null) {
                    try {
                        $filesystem = new Filesystem();
                        $filesystem->remove([$this->getParameter('avatars_directory') . '/' . $oldFileName]);
                    } catch (IOExceptionInterface $ioe) {
                        // ... handle exception if something happens during old file removal
                    }
                }
            } catch (FileException $e) {
                // ... handle exception if something happens during moving uploaded file to avatars directory.
                $fileName = $oldFileName;
            }
        }

        $user2->setAvatar($fileName);

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

        return $this->redirectToRoute('user2_index', [
            'id' => $user2->getId(),
        ]);
    }

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

由于您使用的是Bootstrap主题,因此也请参见此问题Symfony 4 Form file upload field does not show selected filename with Bootstrap 4 theme