Я не могу иметь более 2 отображений vichuploader | Symfony 3.4 - PullRequest
0 голосов
/ 03 января 2019

Я в полном отчаянии !!Я прошу вашей помощи!Прошло уже почти две недели, как я блокирую эту точку, и я почти не сплю по ночам: - (

контекст:

Symfony 3.4 vich-uploder "^ 1.4"

Я получаю это исключение:

SQLSTATE [23000]: Нарушение ограничения целостности: 1048 Столбец 'имя_документа' не может быть пустым

Я объясняю свою проблему:

-Iиметь отношение OneToOne между двумя объектами (NoteFrais и Justificatif).
- У каждого NoteFrais есть один Justificatif.
- Justificatif - это файл vichUplodable.
- Все отлично работает в моей локальной среде.
-проблема возникает только на моей версии на производстве на сервере. В этом же проекте у меня уже есть другое отображение vich_uploader для других отношений между другими объектами. У них все отлично работает.

Вот моя конфигурация:

parameters:
locale: fr
app.path.logos: /uploads/logos
app.path.imports: /uploads/imports
app.path.documents: /uploads/documents

vich_uploader:
db_driver: orm
mappings:
    logo:
        uri_prefix: '%app.path.logos%'
        upload_destination: '%kernel.root_dir%/../web%app.path.logos%'
        namer: vich_uploader.namer_uniqid
        inject_on_load:     false
        delete_on_update:   true
        delete_on_remove:   true
    import:
        uri_prefix: '%app.path.imports%'
        upload_destination: '%kernel.root_dir%/../web%app.path.imports%'
        namer: vich_uploader.namer_uniqid
        inject_on_load:     false
        delete_on_update:   true
        delete_on_remove:   true
    document:
        uri_prefix: '%app.path.documents%'
        upload_destination: '%kernel.root_dir%/../web%app.path.documents%'
        namer: vich_uploader.namer_uniqid
        inject_on_load:     false
        delete_on_update:   true
        delete_on_remove:   true

У меня нет проблем с первыми 2 сопоставлениями (логотипом и импортом) как в локальной среде, так и на сервере prod.

Вот право Justificatify (@ vich / загружаемый)

**
* Justificatif
*
* @ORM\Table(name="justificatif")
* @ORM\Entity(repositoryClass="MKG\MystiBundle\Repository\JustificatifRepository")
* @vich\Uploadable
 */
class Justificatif
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * NOTE: This is not a mapped field of entity metadata, just a simple property.
 *
 * @Vich\UploadableField(mapping="document", fileNameProperty="documentName")
 *
 * @var File
 */
private $justificatifFile;

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


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

/**
 * Constructor
 */
public function __construct()
{
    $this->updatedAt = new \DateTime();
}

/**
 * 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|UploadedFile $justificatif
 */
public function setJustificatifFile(File $justificatif = null)
{
    $this->justificatifFile = $justificatif;

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

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



/**
 *
 * @param $documentName
 *
 * @return $this
 */
public function setDocumentName($documentName)
{
    $this->documentName = $documentName;

    return $this;
}

/**
 * @return string|null
 */
public function getDocumentName()
{
    return $this->documentName;
}

/**
 * Set updatedAt
 *
 * @param \DateTime $updatedAt
 *
 * @return Justificatif
 */
public function setUpdatedAt($updatedAt)
{
    $this->updatedAt = $updatedAt;

    return $this;
}

/**
 * Get updatedAt
 *
 * @return \DateTime
 */
public function getUpdatedAt()
{
    return $this->updatedAt;
}

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

Вот объект NoteFrais (с отношением):

/**
 * NoteFrais
 *
 * @ORM\Table(name="note_frais")
 * @ORM\Entity(repositoryClass="MKG\MystiBundle\Repository\NoteFraisRepository")
 * @Vich\Uploadable
 */
 class NoteFrais
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="MKG\MystiBundle\Entity\Mission", cascade={"persist"})
 * @ORM\JoinColumn(name="mission_id", referencedColumnName="id", onDelete="CASCADE", nullable=true)
 */
private $mission;

/**
 * @ORM\ManyToOne(targetEntity="MKG\MystiBundle\Entity\CodeComptable", cascade={"persist"})
 * @ORM\JoinColumn(name="compte_comptable_id", referencedColumnName="id", onDelete="SET NULL", nullable=true)
 */
private $compteComptable;

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

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

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

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

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

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

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

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

/**
 * @ORM\OneToOne(targetEntity="Justificatif", cascade={"persist"})
 * @ORM\JoinColumn(name="justificatif_id", referencedColumnName="id", onDelete="CASCADE", nullable=true)
 */
private $justificatif;

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


public function __construct() {

    $this->dateCreation = new \DateTime;
    $this->etat = "0";
}



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

//======== Getters et Setters ========//

/**
 * Set justificatif
 *
 * @param \MKG\MystiBundle\Entity\Justificatif $justificatif
 *
 * @return NoteFrais
 */
public function setJustificatif(\MKG\MystiBundle\Entity\Justificatif $justificatif = null)
{
    $this->justificatif = $justificatif;

    return $this;
}

/**
 * @return \MKG\MystiBundle\Entity\Justificatif
 */
public function getJustificatif()
{
    return $this->justificatif;
}

//======== Getters et Setters ========//

}

Форма Justificatif:

public function buildForm(FormBuilderInterface $builder, array $options)
   {
       $builder->add('justificatifFile', FileType::class, array(
       //'data_class' => null,
       'label' => false,
       'required' => true,
       'attr' => array(
           'class' => 'NoteFraisBootstrapFileInput',
           'type' => 'file',
           'placeholder' => 'Selectionner un justificatif (jpeg, png, jpg, pdf)',
           'data-preview-file-type' => 'text',
           'data-allowed-file-extensions' => '["jpeg", "png", "jpg", "pdf"]',
       )
   ));
   }

Я используюFileType вместо VichType работает нормально, поэтому проблема не возникает ...

Вот форма NoteFrais:

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
    //->add('circuit')
  //======Autres champs======//

    ->add('justificatif', JustificatifType::class, array(
        'required' => false));
}

Я много чего перепробовал, пересмотрел мойкод, читать страницы и страницы форума ...

Для информации:

-У меня есть права на папки назначения на сервере.
-Я пытался несколько разизменить имя проблемного сопоставления ...
- Я так много почистил кеш (приобрел, заказал ...)

С другой стороны:

Я заметил, что я 'указываю моей сущности Justificatif на другое существующее отображение, все работает отлично ???Круто ... Но это не то, что я хочу ... Я хочу провести 3 разных матча и хочу понять, почему это 3-е сопоставление игнорируется.

Спасибо тем, кто уделил мне время.: -)

Ответы [ 2 ]

0 голосов
/ 08 января 2019

Я наконец-то решил эту проблему! На самом деле, это было очень глупо ... Проблема касается только среды prod, что означает, что используемая конфигурация должна быть зарегистрирована из файла config_prod.yml, и это не мой случай! Большую часть времени я нахожусь в среде разработчиков, поэтому я перестал игнорировать существование этого файла ... Спасибо всем, кто пытался мне помочь!

0 голосов
/ 04 января 2019

В отношениях вы должны добавить другую форму как EntityType в своем конструкторе форм. Если OneToOne как EntityType и OneToMany как CollectionType.

->add('justificatif', EntityType::class, array(
    'class' => 'YourBundle:Justificatif',
    'required' => false
));

вы также можете добавить nullable true к своему атрибуту $ documentName в Justificatif Entity, чтобы избежать проблем с вставленными пустыми значениями.

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

EDITED Действительно, поле не сохраняется, оно должно быть аннотировано как File в объекте атрибута. Вы можете использовать Vich \ UploaderBundle \ Entity \ File встраиваемый для хранения информации о файле в вашей сущности ORM

В вашем классе Justificatif

/**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     * 
     * @Vich\UploadableField(mapping="document", fileNameProperty="document.name")
     * 
     * @var File
     */
    private $justificatifFile;

    /**
     * @ORM\Embedded(class="Vich\UploaderBundle\Entity\File")
     *
     * @var EmbeddedFile
     */
    private $fileJustificatif;

 /**
     * 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|UploadedFile $justificatifFile
     */
    public function setjustificatifFile(?File $justificatifFile = null)
    {
        $this->justificatifFile = $justificatifFile;

        if (null !== $justificatifFile) {
            // It is required that at least one field changes if you are using doctrine
            // otherwise the event listeners won't be called and the file is lost
            $this->updatedAt = new \DateTimeImmutable();
        }
    }

    public function getjustificatifFile(): ?File
    {
        return $this->justificatifFile;
    }

Из документации https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/usage.md

...