«Аргумент 1, передаваемый в Symfony \ Bridge \ Twig \ Extension \ TranslationExtension :: trans (), должен иметь тип string, значение NULL» - PullRequest
0 голосов
/ 18 апреля 2020

У меня проблема с загрузкой файла PDF с помощью vichUploader. У меня есть эта ошибка ошибка , и это строка, указанная в ошибке строка 214 это мой объект Candidat:

    <?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Entity\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;


/**
 * @ORM\Entity(repositoryClass="App\Repository\CandidatRepository")
 * @UniqueEntity(fields={"email"}, message="There is already an account with this email")
 * @Vich\Uploadable()
 */
class Candidat implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\Column(type="json")
     */
    private $roles = ["ROLE_CANDIDAT"];


    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $cv;
    /**
     * @Vich\UploadableField(mapping="cv_files",fileNameProperty="cv")
     * @Assert\File(
     *      maxSize = "6M",
     *      mimeTypes = {"application/pdf", "application/x-pdf"},
     *      mimeTypesMessage="veuillez télécharger PDF taille-max:6M "
     *  )
     */
    private $cvFile;
    /**
     * @ORM\Column(type="datetime",nullable=true)
     *
     * @var \DateTimeInterface|null
     */
    private $updatedAt;
    /**
     * @ORM\Column(type="string", length=255)
     */
    private $nom;

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

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

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\ApplyOffre", mappedBy="candidat")
     */
    private $applyOffres;

    public function __construct()
    {
        $this->applyOffres = new ArrayCollection();
    }

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

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

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

        return $this;
    }
    /**
     * @ORM\Column(type="string",nullable=true)
     * @Assert\Regex(
     *      pattern="/^(?:0|\(?\+33\)?\s?|0033\s?)[1-79](?:[\.\-\s]?\d\d){4}$/",
     *     message="le numéro est invalide"
     * )
     * @Assert\Length (
     *     min = 10,
     *     max =15,
     *     minMessage = "le numéro de téléphone est de taille<{{limit}}",
     *     maxMessage = "le numéro de téléphone est de taille>{{limit}}",
     *     allowEmptyString = true,
     * )
     */
    private $numeroTelephone;
    /**
     * @return string
     */
    public function getNumeroTelephone():?string
    {
        return $this->numeroTelephone;
    }

    /**
     * @param string $numeroTelephone
     */
    public function setNumeroTelephone($numeroTelephone): void
    {
        $this->numeroTelephone = $numeroTelephone;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string) $this->email;
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = ['ROLE_CANDIDAT','ROLE_USER'];

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }
    /**
     * @see UserInterface
     */
    public function getPassword(): string
    {
        return (string) $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    public function getCv(): ?string
    {
        return $this->cv;
    }

    public function setCv(string $cv): self
    {
        $this->cv = $cv;

        return $this;
    }

    /**
     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
     * of 'UploadedFile' is injected into this setter to trigger the update. If this
     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
     * must be able to accept an instance of 'File' as the bundle will inject one here
     * during Doctrine hydration.
    /**
     * @param File $cvFile
     * @throws \Exception
     */
    public function setCvFile($cvFile): void
    {
        $this->cvFile = $cvFile;
        if($cvFile){
            $this->updatedAt=new \DateTime();
        }
    }

    /**
     * @return File|null
     */
    public function getCvFile():?File
    {
        return $this->cvFile;
    }

    /**
     * @return \DateTime|null
     */
    public function getUpdatedAt(): ?\DateTimeInterface
    {
        return $this->updatedAt;
    }

    /**
     * @param \DateTime $updatedAt
     * @return Candidat
     */
    public function setUpdatedAt(\DateTime $updatedAt): self
    {
        $this->updatedAt = $updatedAt;
    }


    public function getNom(): ?string
    {
        return $this->nom;
    }

    public function setNom(string $nom): self
    {
        $this->nom = $nom;

        return $this;
    }

    public function getPrenom(): ?string
    {
        return $this->prenom;
    }

    public function setPrenom(string $prenom): self
    {
        $this->prenom = $prenom;

        return $this;
    }

    public function getSexe(): ?string
    {
        return $this->sexe;
    }

    public function setSexe(string $sexe): self
    {
        $this->sexe = $sexe;

        return $this;
    }

    public function getCivilite(): ?string
    {
        return $this->civilite;
    }

    public function setCivilite(string $civilite): self
    {
        $this->civilite = $civilite;

        return $this;
    }
    /**
     * @return string
     */
    public function getDescription():?string
    {
        return $this->description;
    }

    /**
     * @param string $description
     */
    public function setDescription($description): void
    {
        $this->description = $description;
    }
    /**
     * @return string
     */
    public function getEtude():?string
    {
        return $this->etude;
    }

    /**
     * @param string $etude
     */
    public function setEtude($etude): void
    {
        $this->etude = $etude;
    }
    /**
     * @return Collection|ApplyOffre[]
     */
    public function getApplyOffres(): Collection
    {
        return $this->applyOffres;
    }

    public function addApplyOffre(ApplyOffre $applyOffre): self
    {
        if (!$this->applyOffres->contains($applyOffre)) {
            $this->applyOffres[] = $applyOffre;
            $applyOffre->setCandidat($this);
        }

        return $this;
    }

    public function removeApplyOffre(ApplyOffre $applyOffre): self
    {
        if ($this->applyOffres->contains($applyOffre)) {
            $this->applyOffres->removeElement($applyOffre);
            // set the owning side to null (unless already changed)
            if ($applyOffre->getCandidat() === $this) {
                $applyOffre->setCandidat(null);
            }
        }

        return $this;
    }
    public function __toString()
    {
        return $this->getEmail();
    }

}

и это vichuploader.yaml

vich_uploader:
db_driver: orm
mappings:
    featured_files:
        uri_prefix: '%app.path.featured_files%'
        upload_destination: '%kernel.project_dir%/public%app.path.featured_files%'

    cv_files:
        uri_prefix: /pdf
        upload_destination:  '%kernel.project_dir%/public/pdf'

и это форма регистрации:

    <?php

namespace App\Form;

use App\Entity\Candidat;
use App\Entity\Entreprise;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\TelType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Constraints\IsTrue;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Vich\UploaderBundle\Form\Type\VichFileType;

class RegistrationFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email')
            ->add('agreeTerms', CheckboxType::class, [
                'mapped' => false,
                'constraints' => [
                    new IsTrue([
                        'message' => 'You should agree to our terms.',
                    ]),
                ],
            ])
            ->add('plainPassword', PasswordType::class, [
                // instead of being set onto the object directly,
                // this is read and encoded in the controller
                'mapped' => false,
                'constraints' => [
                    new NotBlank([
                        'message' => 'Please enter a password',
                    ]),
                    new Length([
                        'min' => 6,
                        'minMessage' => 'Your password should be at least {{ limit }} characters',
                        // max length allowed by Symfony for security reasons
                        'max' => 4096,
                    ]),
                ],
            ])

            ->add('nom',TextType::class)
            ->add('cvFile',VichFileType::class)
            ->add('prenom',TextType::class)
            ->add('civilite',ChoiceType::class,[
                'choices'=>[
                    'madame'=>'madame',
                    'monsieur'=>'mr'
                ]
            ])
            ->add('sexe',ChoiceType::class,[
                'choices'=>[
                    'femme'=>'f',
                    'homme'=>'h'
                ]
            ])


        ;
    }

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

Я попытался изменить VichFileTyoe с помощью FileType, и есть ошибки нет, поэтому я не понял, откуда возникла ошибка (потому что я уже использую этот пакет в шаблоне easyAdmin для загрузки изображений, и он работает). Я не знаю, как ее исправить или откуда она появилась.

...