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

On edit, FileType is empty even with setting newFile

编辑时的文件类型保持为空,即使在开头设置新文件也是如此。

我试过将值放在表单中,在创建表单之前设置文件名,但仍然是空的。我使用 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'])`

我想在我的下载字段中获取文件,但我收到此错误:"string"、"NULL" 类型的预期参数在 属性 路径“avatar

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

  1. 在要上传的实体 属性 '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;

如果 'avatar' 持有 non-image 文件,例如 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
  2. 添加的类型提示
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()函数中,因为avatar是可选的,所以代码需要检查一个null avatar。
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 主题,请参阅此问题