2015-08-04 1 views
0

У меня есть одна-много взаимосвязей между прототипом и изображением, у одного прототипа может быть много изображений. Я пытался использовать vich, и вот что у меня есть: Я могу загружать изображения, но не в одно и то же время. Мне нужно отредактировать, сохранить, а затем загрузить второй. Плюс я хочу иметь возможность загружать несколько изображений в каждом разделе: рабочий стол, планшет и мобильный. Вот код моего PrototypeAdmin:Администрирование Sonata Загрузка изображений с помощью vich

<?php 


namespace AppBundle\Admin; 

use Sonata\AdminBundle\Admin\Admin; 
use Sonata\AdminBundle\Datagrid\ListMapper; 
use Sonata\AdminBundle\Datagrid\DatagridMapper; 
use Sonata\AdminBundle\Form\FormMapper; 
use Sonata\AdminBundle\Show\ShowMapper; 

class PrototypeAdmin extends Admin 
{ 

protected function configureFormFields(FormMapper $formMapper) 
{ 
    $formMapper 
     ->with('Général') 
      ->add('nom', 'text', array('label' => 'Nom')) 
      ->add('description','text',array('label'=>'Description')) 
      ->add('dateCreation', 'date', array('label' => 'Date de création')) 

      ->add('projet','entity',array('class' => 'AppBundle\Entity\Projet')) 
     ->end() 

     ->with('Desktop') 
      ->add('images', 'sonata_type_collection', array('data_class' => null),array(
       'edit' => 'inline', 
       'inline' => 'table' 
      )) 
     ->end() 

     ->with('Tablette') 
      ->add('images', 'sonata_type_collection', array('data_class' => null),array(
       'edit' => 'inline', 
       'inline' => 'table' 
      )) 
     ->end() 

     ->with('Mobile') 
      ->add('images', 'sonata_type_collection', array('data_class' => null),array(
       'edit' => 'inline', 
       'inline' => 'table' 
      )) 
     ->end() 

     ->with('Dossier Complet') 
      ->add('file', 'file', array('required' => false , 'label' => 'Dossier complet')) 
     ->end() 
    ; 

} 


protected function configureDatagridFilters(DatagridMapper $datagridMapper) 
{ 
    $datagridMapper 
     ->add('nom') 
     ->add('dateCreation') 
     ->add('projet.id') 
    ; 
} 


protected function configureListFields(ListMapper $listMapper) 
{ 

    $listMapper 
     ->add('nom') 
     ->add('description') 
     ->add('dateCreation') 
     ->add('_action', 'actions', array(
       'actions' => array(
       'show' => array(), 
       'delete' => array(), 
      ) 
     )) 

    ; 
} 
} 

Сначала я могу загрузить в разделе «Desktop», но не в «Tablette» и «Mobile».

Тогда вот мой ImageAdmin:

<?php 


namespace AppBundle\Admin; 

use Sonata\AdminBundle\Admin\Admin; 
use Sonata\AdminBundle\Datagrid\ListMapper; 
use Sonata\AdminBundle\Datagrid\DatagridMapper; 
use Sonata\AdminBundle\Form\FormMapper; 
use Sonata\AdminBundle\Show\ShowMapper; 

class ImageAdmin extends Admin 
{ 

protected function configureFormFields(FormMapper $formMapper) 
{ 
    $formMapper 


      ->add('commentaire','text',array('label'=>'Commentaire')) 
      ->add('typeDevice', 'text', array('label' => 'Type de device')) 
      ->add('image', 'file', array('required' => false , 'label' => 'image')) 
      ->add('prototype','entity',array('class' => 'AppBundle\Entity\Prototype')) 


    ; 
} 


protected function configureDatagridFilters(DatagridMapper $datagridMapper) 
{ 

} 


protected function configureListFields(ListMapper $listMapper) 
{ 

} 
} 

Вот мои две сущности:

Prototype.php:

<?php 

namespace AppBundle\Entity; 

use Doctrine\ORM\Mapping as ORM; 
use Symfony\Component\HttpFoundation\File\File; 
use Vich\UploaderBundle\Mapping\Annotation as Vich; 

/** 
* Prototype 
* 
* @ORM\Table() 
* @ORM\Entity(repositoryClass="AppBundle\Entity\PrototypeRepository") 
* @Vich\Uploadable 
* @ORM\HasLifecycleCallbacks 
*/ 
class Prototype 
{ 
/** 
* @var integer 
* 
* @ORM\Column(name="id", type="integer") 
* @ORM\Id 
* @ORM\GeneratedValue(strategy="AUTO") 
*/ 
private $id; 

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


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

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


/** 
* @ORM\Column(type="string", length=255, name="fichier_nom") 
* 
* @var string $nomFichier 
*/ 
public $nomFichier; 


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


    /** 
    * Unmapped property to handle file uploads 
    * @Vich\UploadableField(mapping="prototype_fichier", fileNameProperty="nomFichier") 
    * 
    * @var File $file 
    */ 
private $file; 


/** 
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Projet", inversedBy="prototypes") 
* @ORM\joinColumn(name="projet_id", referencedColumnName="id") 
*/ 
private $projet; 


    /** 
    * @ORM\OneToMany(targetEntity="AppBundle\Entity\Image", mappedBy="prototype",cascade={"persist"} , orphanRemoval=true) 
    * @ORM\OrderBy({"id"="ASC"}) 
    */ 
protected $images; 


public function __construct() 
{ 
    $this->images = new \Doctrine\Common\Collections\ArrayCollection(); 
    $this->dateCreation = new \DateTime("now"); 
    $this->nom = ""; 
    $this->description = " "; 

} 


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


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

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

/** 
* Set nom 
* 
* @param string $nom 
* @return Prototype 
*/ 
public function setNom($nom) 
{ 
    $this->nom = $nom; 

    return $this; 
} 


/** 
* Set description 
* 
* @param string $description 
* @return Prototype 
*/ 
public function setDescription($description) 
{ 
    $this->description = $description; 

    return $this; 
} 

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

/** 
* Set dateCreation 
* 
* @param \DateTime $dateCreation 
* @return Prototype 
*/ 
public function setDateCreation($dateCreation) 
{ 
    $this->dateCreation = $dateCreation; 

    return $this; 
} 

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


/** 
* Set projet 
* 
* @param \AppBundle\Entity\Projet $projet 
* @return Prototype 
*/ 
public function setProjet(\AppBundle\Entity\Projet $projet = null) 
{ 
    $this->projet = $projet; 
    return $this; 
} 

/** 
* Get projet 
* 
* @return \AppBundle\Entity\Projet 
*/ 
public function getProjet() 
{ 
    return $this->projet; 
} 



/** 
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance 
* 
* @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $file 
*/ 
public function setFile(File $file = null) 
{ 
    $this->file = $file; 

    if ($file) { 

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

/** 
* @return File 
*/ 
public function getFile() 
{ 
    return $this->file; 
} 

/** 
* @param string $nomFichier 
*/ 
public function setNomFichier($nomFichier) 
{ 
    $this->nomFichier = $nomFichier; 
} 

/** 
* @return string 
*/ 
public function getNomFichier() 
{ 
    return $this->nomFichier; 
} 



public function setImages($images) 
{ 
if (count($images) > 0) { 
    foreach ($images as $i) { 
     $this->addImages($i); 
    } 
} 

return $this; 
} 

/** 
* Add images 
* 
* @param \AppBundle\Entity\Image $images 
* @return Prototype 
*/ 
public function addImages(\AppBundle\Entity\Image $images) 
{ 
$this->images[]= $images; 
return $this; 
} 

public function addImage(\AppBundle\Entity\Image $image) 
{ 
$image->setPrototype($this); 
$this->images->add($image); 
} 


/** 
* Remove images 
* 
* @param \AppBunble\Entity\Image $images 
*/ 
public function removeImages(\AppBundle\Entity\Image $images) 
{ 
$this->images->removeElement($images); 
} 


/** 
* Get images 
* 
* @return \Doctrine\Common\Collections\Collection 
*/ 

public function getImages() 
{ 
return $this->images; 
} 
} 

И image.php

<?php 

namespace AppBundle\Entity; 

use Doctrine\ORM\Mapping as ORM; 
use Symfony\Component\HttpFoundation\File\File; 
use Vich\UploaderBundle\Mapping\Annotation as Vich; 

/** 
* Prototype 
* 
* @ORM\Table() 
* @ORM\Entity(repositoryClass="AppBundle\Entity\PrototypeRepository") 
* @Vich\Uploadable 
* @ORM\HasLifecycleCallbacks 
*/ 
class Prototype 
{ 
/** 
* @var integer 
* 
* @ORM\Column(name="id", type="integer") 
* @ORM\Id 
* @ORM\GeneratedValue(strategy="AUTO") 
*/ 
private $id; 

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


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

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


/** 
* @ORM\Column(type="string", length=255, name="fichier_nom") 
* 
* @var string $nomFichier 
*/ 
public $nomFichier; 


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


    /** 
    * Unmapped property to handle file uploads 
    * @Vich\UploadableField(mapping="prototype_fichier", fileNameProperty="nomFichier") 
    * 
    * @var File $file 
    */ 
private $file; 


/** 
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Projet", inversedBy="prototypes") 
* @ORM\joinColumn(name="projet_id", referencedColumnName="id") 
*/ 
private $projet; 


/** 
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Image", mappedBy="prototype",cascade={"persist"} , orphanRemoval=true) 
* @ORM\OrderBy({"id"="ASC"}) 
*/ 
protected $images; 


public function __construct() 
{ 
    $this->images = new \Doctrine\Common\Collections\ArrayCollection(); 
    $this->dateCreation = new \DateTime("now"); 
    $this->nom = ""; 
    $this->description = " "; 

} 


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


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

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

/** 
* Set nom 
* 
* @param string $nom 
* @return Prototype 
*/ 
public function setNom($nom) 
{ 
    $this->nom = $nom; 

    return $this; 
} 


/** 
* Set description 
* 
* @param string $description 
* @return Prototype 
*/ 
public function setDescription($description) 
{ 
    $this->description = $description; 

    return $this; 
} 

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

/** 
* Set dateCreation 
* 
* @param \DateTime $dateCreation 
* @return Prototype 
*/ 
public function setDateCreation($dateCreation) 
{ 
    $this->dateCreation = $dateCreation; 

    return $this; 
} 

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


/** 
* Set projet 
* 
* @param \AppBundle\Entity\Projet $projet 
* @return Prototype 
*/ 
public function setProjet(\AppBundle\Entity\Projet $projet = null) 
{ 
    $this->projet = $projet; 
    return $this; 
} 

/** 
* Get projet 
* 
* @return \AppBundle\Entity\Projet 
*/ 
public function getProjet() 
{ 
    return $this->projet; 
} 



/** 
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance 
* 
* @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $file 
*/ 
public function setFile(File $file = null) 
{ 
    $this->file = $file; 

    if ($file) { 

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

/** 
* @return File 
*/ 
public function getFile() 
{ 
    return $this->file; 
} 

/** 
* @param string $nomFichier 
*/ 
public function setNomFichier($nomFichier) 
{ 
    $this->nomFichier = $nomFichier; 
} 

/** 
* @return string 
*/ 
public function getNomFichier() 
{ 
    return $this->nomFichier; 
} 



public function setImages($images) 
{ 
if (count($images) > 0) { 
    foreach ($images as $i) { 
     $this->addImages($i); 
    } 
} 

return $this; 
} 

/** 
* Add images 
* 
* @param \AppBundle\Entity\Image $images 
* @return Prototype 
*/ 
public function addImages(\AppBundle\Entity\Image $images) 
{ 
$this->images[]= $images; 
return $this; 
} 

public function addImage(\AppBundle\Entity\Image $image) 
{ 
$image->setPrototype($this); 
$this->images->add($image); 
} 


/** 
* Remove images 
* 
* @param \AppBunble\Entity\Image $images 
*/ 
public function removeImages(\AppBundle\Entity\Image $images) 
{ 
$this->images->removeElement($images); 
} 


/** 
* Get images 
* 
* @return \Doctrine\Common\Collections\Collection 
*/ 

public function getImages() 
{ 
return $this->images; 
} 

} 

I я только начал использовать S ymfony и Sonata И, возможно, есть еще один способ сделать это.

Edit:

Я только что проверил mediaBundle, я, следуя инструкциям, приведенным в документации. Нужно ли генерировать объекты с помощью этой команды

php app/console sonata:easy-extends:generate --dest=src SonataMediaBundle 

Возможно, я могу внести изменения в свои собственные сущности?

+0

Я не использовал vichuploader в то время, но я помню, что он не мог обрабатывать несколько загрузок. – Hakim

ответ

0

Ваш вопрос, кажется, не быть непосредственно связаны с VichUploaderBundle, вы, вероятно, просто нужно добавить два варианта ваших images полей: allow_add и allow_delete (как установлено в true). Вы также можете установить by_reference на номер false.

Я реализовал то, чего вы хотите достичь в my sandbox.

+0

Я пытался это сделать, но у меня по-прежнему возникает одна и та же проблема: каждый раз, когда я нажимаю «добавить», чтобы добавить другое изображение, которое загружает страница, и я теряю первое изображение, на самом деле мне все равно приходится загружать один за другим. У меня есть это: '-> add (' images ',' sonata_type_collection ', array ( ' type_options '=> array (' allow_add '=> true,' allow_delete '=> true,' by_reference '=> false)), array ('data_class' => null), array ( 'edit' => 'inline', 'inline' => 'table' )) ' –

Смежные вопросы