I'm trying to get my form working since two days.
I'm reading the chapter "Forms" in the Symfony book up and down but i don't know what I'm doing wrong.
This is my Entity class:
/**
* Homecontent
*
* #ORM\Table(name="homecontent", indexes={#ORM\Index(name="id_idx", columns={"author_id"})})
* #ORM\Entity()
*/
class Homecontent
{
/**
* #var integer
*
* #ORM\Column(name="home_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $homeId;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime", nullable=false)
*/
private $date;
/**
* #var string
*
* #ORM\Column(name="title", type="text", nullable=false)
*
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="content", type="text", nullable=false)
*/
private $content;
/**
* #var string
*
* #ORM\Column(name="picture_path", type="text", nullable=false)
*/
private $picturePath;
/**
* #var \Contentuser
*
* #ORM\ManyToOne(targetEntity="Contentuser")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="author_id", referencedColumnName="content_user_id")
* })
*/
private $author;
This is my controller:
/**
* #param $request
* #return \Symfony\Component\HttpFoundation\Response
* #Route("/content/insert")
*/
public function indexAction(Request $request)
{
$content = new HomecontentType();
$form = $this->createForm(HomecontentType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()
->getManager();
$em->persist($content);
$em->flush();
return $this->redirectToRoute('worked check index');
}
return $this->render('Form/ContentForm.html.twig', array('form' => $form->createView()));
And this is my Form Class:
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('content')
->add('picturePath')
->add('date',DateTimeType::class)
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Homecontent'
));
}
}
I use twig for the rendering and it's working, but when i want to submit it i get an error
The class 'AppBundle\Form\HomecontentType' was not found in the chain configured namespaces AppBundle\Entity
I'm sorry for the long code section.
Thanks in advance!
At the beginning of the indexAction you have error, the correct code is:
$content = new Homecontent();
$form = $this->createForm(HomecontentType::class, $content);
Related
In my Symfony 3.4 project (vich/uploader-bundle: "^1.4"), I need to upload 3 kinds of files and for two of them it's work, but for the third even if i use the same process it doesn't work...? When the form is submitted, i get this exception:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'document_name' cannot be null
when i dumped, i can see that my Setter "vichuploader document name" not work and can't persisted.
This is the context:
*Everythings is ok on my local version...Files are uploaded but on my production version it's doesn't work.
*I have one Entity (NoteFrais) with OneToOne relation with another Entity (Justificatif).
*The Justificatif entity has the #vich\uploadable annotation
I followed the documentation, read many tuto, ask question on stackverflow, cleared cache and updated doctrine schema many times, tried many things...
******config.yml********
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%' //========IT'S WORK FINE FOR THIS ONE==========//
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%' //=========IT'S WORK FINE THIS ONE=========//
namer: vich_uploader.namer_uniqid
# inject_on_load: true important!!
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: true important!!
inject_on_load: false
delete_on_update: true
delete_on_remove: true
******JustificatifType*******
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('justificatifFile', FileType::class, array( //========= I TRIED WITH FILETYPE OR VICHFILETYPE =======//
//'data_class' => null, //======== NOTE:USALLY I USE TO FILETYPE AND IT'S WORK FINE ==============//
'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"]',
)
));
}
******NoteFraisType**********
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
//=======OTHERS FIELDS===========//
->add('justificatif', JustificatifType::class, array(
'required' => false));
}
*****Justificatif.php (Entity)*****
<?php
namespace MKG\MystiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as 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 (Entity)*********
<?php
namespace MKG\MystiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* NoteFrais
*
* #ORM\Table(name="note_frais")
* #ORM\Entity(repositoryClass="MKG\MystiBundle\Repository\NoteFraisRepository")
*/
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;
}
/**
* Set montantDefraiementMax
*
* #param string $montantDefraiementMax
*
* #return NoteFrais
*/
public function setMontantDefraiementMax($montantDefraiementMax)
{
$this->montantDefraiementMax = $montantDefraiementMax;
return $this;
}
/**
* Get montantDefraiementMax
*
* #return string
*/
public function getMontantDefraiementMax()
{
return $this->montantDefraiementMax;
}
/**
* Set refacturationClient
*
* #param string $refacturationClient
*
* #return NoteFrais
*/
public function setRefacturationClient($refacturationClient)
{
$this->refacturationClient = $refacturationClient;
return $this;
}
/**
* Get refacturationClient
*
* #return string
*/
public function getRefacturationClient()
{
return $this->refacturationClient;
}
/**
* Set compteAvancesEtAcomptes
*
* #param string $compteAvancesEtAcomptes
*
* #return NoteFrais
*/
public function setCompteAvancesEtAcomptes($compteAvancesEtAcomptes)
{
$this->compteAvancesEtAcomptes = $compteAvancesEtAcomptes;
return $this;
}
/**
* Get compteAvancesEtAcomptes
*
* #return string
*/
public function getCompteAvancesEtAcomptes()
{
return $this->compteAvancesEtAcomptes;
}
/**
* Set currentUser
*
* #param string $currentUser
*
* #return NoteFrais
*/
public function setCurrentUser($currentUser)
{
$this->currentUser = $currentUser;
return $this;
}
/**
* Get currentUser
*
* #return string
*/
public function getCurrentUser()
{
return $this->currentUser;
}
/**
* Set codeAffaire
*
* #param string $codeAffaire
*
* #return NoteFrais
*/
public function setCodeAffaire($codeAffaire)
{
$this->codeAffaire = $codeAffaire;
return $this;
}
/**
* Get codeAffaire
*
* #return string
*/
public function getCodeAffaire()
{
return $this->codeAffaire;
}
/**
* Set etat
*
* #param string $etat
*
* #return NoteFrais
*/
public function setEtat($etat)
{
$this->etat = $etat;
return $this;
}
/**
* Get etat
*
* #return string
*/
public function getEtat()
{
return $this->etat;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
*
* #return NoteFrais
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
/**
* Set mission
*
* #param \MKG\MystiBundle\Entity\Mission $mission
*
* #return NoteFrais
*/
public function setMission(\MKG\MystiBundle\Entity\Mission $mission = null)
{
$this->mission = $mission;
return $this;
}
/**
* Get mission
*
* #return \MKG\MystiBundle\Entity\Mission
*/
public function getMission()
{
return $this->mission;
}
/**
* Set compteComptable
*
* #param \MKG\MystiBundle\Entity\CodeComptable $compteComptable
*
* #return NoteFrais
*/
public function setCompteComptable(\MKG\MystiBundle\Entity\CodeComptable $compteComptable = null)
{
$this->compteComptable = $compteComptable;
return $this;
}
/**
* Get compteComptable
*
* #return \MKG\MystiBundle\Entity\CodeComptable
*/
public function getCompteComptable()
{
return $this->compteComptable;
}
/**
* 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 File
*/
public function getJustificatif()
{
return $this->justificatif;
}
/**
* Set totalDefraiement
*
* #param string $totalDefraiement
*
* #return NoteFrais
*/
public function setTotalDefraiement($totalDefraiement)
{
$this->totalDefraiement = $totalDefraiement;
return $this;
}
/**
* Get totalDefraiement
*
* #return string
*/
public function getTotalDefraiement()
{
return $this->totalDefraiement;
}
/**
* Set totalRefacturation
*
* #param string $totalRefacturation
*
* #return NoteFrais
*/
public function setTotalRefacturation($totalRefacturation)
{
$this->totalRefacturation = $totalRefacturation;
return $this;
}
/**
* Get totalRefacturation
*
* #return string
*/
public function getTotalRefacturation()
{
return $this->totalRefacturation;
}
}
********* newAction in NoteFraisController *********
/**
* Creates a new noteFrais entity.
*
*/
public function newAction(Request $request)
{
// === RECUPERE LA MISSION
$em = $this->getDoctrine()->getManager();
$mission = $em->getRepository('MKGMystiBundle:Mission')->findOneBy(array('id' => $request->get('idMission')));
$lignesNoteFrais = $em->getRepository('MKGMystiBundle:NoteFrais')->findBy(array('mission' => $mission->getId()));
$noteFrais = new Notefrais();
$form = $this->createForm('MKG\MystiBundle\Form\NoteFraisType', $noteFrais);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//$noteFrais->setMission($mission);
$em = $this->getDoctrine()->getManager();
$em->persist($noteFrais);
//dump($noteFrais);die();
$em->flush();
$this->addFlash('notice', 'Une ligne a été ajouté à la note de frais!');
return $this->redirect($request->getUri());
}
return $this->render('#MKGMysti/Notefrais/new.html.twig', array(
'lignesNoteFrais' => $lignesNoteFrais,
'mission' => $mission,
'noteFrais' => $noteFrais,
'form' => $form->createView(),
));
}
Thank you very much your time!!!!
I have a form which save queries. This is organized in the way of a people who ask is saved also this create a threat where is saving the id_question and emailperson. The issue is that the same person does another question. Logically, this report a primary key error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'drj00003#ujaen.es' for key 'PRIMARY'
How do I fix it? In the constructor of class I cannot check if this exists and all registers are generated automatically in cascade without form.
It should be easy but I can't solve this.
class HiloType extends AbstractType{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('consultanteemail', new ConsultanteType(), array ('label' => false))
->add('personalemail', 'entity', array(
'label' => 'Personal de Soporte',
'class' => 'GuiasDocentes\AppBundle\Entity\Personal',
'property' => 'Enunciado',
'by_reference' => 'false',
'query_builder' => function(PersonalRepository $pr) {
$query= $pr->createQueryBuilder('u')
;
return $query;
},
'empty_value' => 'Elige un perfil de consulta:',
))
;
}
...
class Hilo{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \GuiasDocentes\AppBundle\Entity\Personal
*
* #ORM\ManyToOne(targetEntity="Personal", inversedBy="hilos", cascade ={"ALL"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="personalEmail", referencedColumnName="email")
* })
*/
private $personalemail;
/**
* #var \GuiasDocentes\AppBundle\Entity\Consultante
*
* #ORM\ManyToOne(targetEntity="Consultante", inversedBy="hilos", cascade ={"ALL"} )
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="consultanteEmail", referencedColumnName="email")
* })
*/
private $consultanteemail;
/* Customized code */
/**
* #ORM\OneToMany(targetEntity="GuiasDocentes\AppBundle\Entity\Consulta", mappedBy="hiloid")
* #Assert\Valid()
*/
private $consultas;
public function __construct(){
$this->consultas = new ArrayCollection();
}
public function setConsultas (Consulta $consulta){
$this->hilos[]=$consulta;
}
public function addConsulta (\GuiasDocentes\AppBundle\Entity\Consulta $consulta){
$this->hilos[] = $consulta;
}
/* End customized code */
...
class Consultante{
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=50, nullable=false)
* #ORM\Id
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="nombre", type="string", length=30, nullable=true)
*/
private $nombre;
/**
* #var string
*
* #ORM\Column(name="apellidos", type="string", length=50, nullable=true)
*/
private $apellidos;
/* Customized code */
/**
* #ORM\OneToMany(targetEntity="GuiasDocentes\AppBundle\Entity\Hilo", mappedBy="consultanteemail")
* #Assert\Valid()
*/
private $hilos;
public function __construct(){
$this->hilos = new ArrayCollection();
}
public function setHilos (Hilo $hilo){
$this->hilos[]=$hilo;
}
public function addHilo (\GuiasDocentes\AppBundle\Entity\Hilo $hilo){
$this->hilos[] = $hilo;
}
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/* End customize code */
...
public function contactoAction (Request $request){
$session = $request->getSession();
$perfil = $session->get('perfil');
$consultaHasAsignatura = new ConsultaHasAsignatura();
$form = $this->createForm(new ConsultaHasAsignaturaType(), $consultaHasAsignatura);
if ($request->isMethod('POST')){
$form->handleRequest($request);
if($form->isValid()){
$em = $this->getDoctrine()->getManager();
$em->persist($consultaHasAsignatura);
$em->flush();
return $this->redirectToRoute('guias_docentes_app_homepage');
}
}
return $this->render('GuiasDocentesAppBundle:FAQ:contacto.html.twig', array('perfil'=>$perfil,
'form' => $form->createView()
));
}
I have two entities in my code: Session and SessionPicture.
There is a OneToOne relationship between Session and SessionPicture. Session is the mapping entity and SessionPicture the inverse one.
I have a SessionType form, which embeds a SessionPictureType form. I would like the user to be able to upload an image for each session when he fille the SessionType form.
The SessionPicture class contains a file attribute (UploadedFile class) and I have used LifecycleEvents to upload the image file and save it in the right directory.
This is what my code looks for the session class:
/**
* Session
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="MyBundle\Entity\SessionRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Session
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* #ORM\OneToOne(targetEntity="MyBundle\Entity\SessionPicture", cascade={"persist", "remove"}, inversedBy="session")
* #ORM\JoinColumn(name="session_picture_id", referencedColumnName="id", nullable=true)
*/
private $sessionPicture;
/**
* Set name
*
* #param string $name
*
* #return Session
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set sessionPicture
*
* #param \MyBundle\Entity\SessionPicture $sessionPicture
*
* #return Session
*/
public function setSessionPicture(MyBundle\Entity\SessionPicture $sessionPicture = null)
{
$this->sessionPicture = $sessionPicture;
return $this;
}
/**
* Get sessionPicture
*
* #return \MyBundle\Session\SessionPicture
*/
public function getSessionPicture()
{
return $this->sessionPicture;
}
And this one for my SessionPicture class:
/**
* SessionPicture
*
* #ORM\Table(name="at_session_picture")
* #ORM\Entity(repositoryClass="MyBundle\Entity\SessionPictureRepository")
* #ORM\HasLifecycleCallbacks()
*/
class SessionPicture
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="extension", type="string", length=255)
*/
private $extension;
/**
* #var string
*
* #ORM\Column(name="alt", type="string", length=255)
*/
private $alt;
/**
* #var string
*
* #ORM\Column(name="path", type="string", length=255, nullable=true)
*/
private $path;
/**
* #ORM\OneToOne(targetEntity="MyBundle\Entity\Session", mappedBy="sessionPicture")
*/
private $session;
public $file;
private $fileNameForRemove;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set extension
*
* #param string $extension
*
* #return SessionPicture
*/
public function setExtension($extension)
{
$this->extension = $extension;
return $this;
}
/**
* Get extension
*
* #return string
*/
public function getExtension()
{
return $this->extension;
}
/**
* Set alt
*
* #param string $alt
*
* #return SessionPicture
*/
public function setAlt($alt)
{
$this->alt = $alt;
return $this;
}
/**
* Get alt
*
* #return string
*/
public function getAlt()
{
return $this->alt;
}
/**
* Set path
*
* #param string $path
*
* #return SessionPicture
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set session
*
* #param \MyBundle\Entity\Session $session
*
* #return SessionPicture
*/
public function setSession(\NyBundle\Entity\Session $session = null)
{
$this->session = $session;
return $this;
}
/**
* Get session
*
* #return \MyBundle\Entity\Session
*/
public function getSession()
{
return $this->session;
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if($this->file === null)
return ;
$extension = $this->file->guessExtension();
$name = $this->getSession()->getName();
$this->extension = (string)$extension;
$this->alt = (string)strval($name);
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
$this->path = $this->alt.'.'.$this->extension;
if ($this->file === null)
return ;
$this->file->move($this->getUploadRootDir(), $this->path);
unset($this->file);
}
I would like to draw your attention on the preUpload() function in my SessionPicture.php
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if($this->file === null)
return ;
$extension = $this->file->guessExtension();
$name = $this->getSession()->getName();
$this->extension = (string)$extension;
$this->alt = (string)strval($name);
}
I use this function to give my SessionPicture the same name as the mapping session name and save it in my server with the same name after form validation. Below is an excerpt of my SessionType.php. As you can notice, I embedded a SessionPictureType inside my SessionType.
class SessionType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array(
'required' => true
))
->add('sessionPicture', new SessionPictureType(), array(
'required' => false
))
->add('Submit', 'submit');
When I validate this form, I get the error
Error: Call to a member function getName() on a non-object
It seems that in my preUpload() function in my SessionPicture.php, trying to call $this->getSession() returns nothing instead of returning the mapping session. The same applies if I use $this->getSession() in the upload function.
Can anyone help with that? How can I get the mapping entity before or during form validation and use it in my inversing entity to update its attributes?
Many thanks in advance.
Could anyone give me a hand please?
I need to implement the list of books and readers using Sonata admin bundle.
The problem is that I get empty column of read books for each reader in the list.
Forein keys are written okay to the DB.
Please see the code:
ReadersAdmin Class
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('name')
->add('book',
'entity',
array(
'class' => 'AppBundle:Books',
'property' => 'name',
'multiple' => true,
'expanded' => true
)
);
}
/**
* #param \Sonata\AdminBundle\Show\ShowMapper $showMapper
*
* #return void
*/
protected function configureShowField(ShowMapper $showMapper)
{
$showMapper
->add('name')
->add('book')
;
}
/**
* #param \Sonata\AdminBundle\Datagrid\ListMapper $listMapper
*
* #return void
*/
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('name')
->add('book')
->add('_action', 'input', array(
'actions' => array(
'show' => array(),
'edit' => array(),
'delete' => array(),
)
))
;
}
ReadersRelations Entity
class ReadersRelations
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Books
*
* #ORM\ManyToOne(targetEntity="\AppBundle\Entity\Books", inversedBy="ReadersRelations")
* #ORM\JoinColumn(name="book_id", referencedColumnName="id")
*/
private $book;
/**
* #var Readers
*
* #ORM\ManyToOne(targetEntity="\AppBundle\Entity\Readers", inversedBy="ReadersRelations")
* #ORM\JoinColumn(name="reader_id", referencedColumnName="id")
*/
private $reader;
Books Entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Books
*
* #ORM\Entity
* #ORM\Table(name="Books")
*/
class Books
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="author", type="string", length=255)
*
*/
private $author;
/**
* #var ReadersRelations
*
* #ORM\OneToMany(targetEntity="\AppBundle\Entity\ReadersRelations" , mappedBy="Books" , cascade={"all"})
*/
private $readers;
public function __toString()
{
return $this->name;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Books
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set author
*
* #param string $author
* #return Books
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return string
*/
public function getAuthor()
{
return $this->author;
}
}
Readers Entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use AppBundle\Entity\ReadersRelations;
/**
* Readers
*
* #ORM\Entity
* #ORM\Table(name="Readers")
*/
class Readers
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO") *
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* */
private $name;
/**
* #var ReadersRelations
*
* #ORM\OneToMany(targetEntity="\AppBundle\Entity\ReadersRelations" , mappedBy="Readers" , cascade={"all"})
*/
private $book;
private $books;
public function __construct()
{
$this->book = new ArrayCollection();
$this->books = new ArrayCollection();
}
public function __toString()
{
return $this->name;
}
public function getBook()
{
$books = new ArrayCollection();
foreach($books as $p)
{
$books[] = $p->getBook();
}
return $books;
}
public function setBook($books)
{
foreach($books as $p)
{
$po = new ReadersRelations();
$po->setBook($p);
$po->setReader($this);
$this->addPo($po);
}
}
public function addPo($ProductOrder)
{
$this->book[] = $ProductOrder;
}
public function removePo($ProductOrder)
{
return $this->book->removeElement($ProductOrder);
}
class Readers
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO") *
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* */
private $name;
/**
* #var ReadersRelations
*
* #ORM\OneToMany(targetEntity="\AppBundle\Entity\ReadersRelations" , mappedBy="Readers" , cascade={"all"})
*/
private $book;
private $books;
public function __construct()
{
$this->book = new ArrayCollection();
$this->books = new ArrayCollection();
}
public function __toString()
{
return $this->name;
}
public function getBook()
{
$books = new ArrayCollection();
foreach($books as $p)
{
$books[] = $p->getBook();
}
return $books;
}
public function setBook($books)
{
foreach($books as $p)
{
$po = new ReadersRelations();
$po->setBook($p);
$po->setReader($this);
$this->addPo($po);
}
}
public function addPo($ProductOrder)
{
$this->book[] = $ProductOrder;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Readers
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
So, have you problem for store data using your relationship ? Or juste for get data in list ?
If it's for save data, try to implement Sonata type collection or Sonata type model field types for register new related entries.
Then, if you have any problems, we will check if your entities setters have missing actions.
I'm trying to create a form to insert "questions" that can have one or more "answers". So I want to add an embed form for the Answer entity.
It seems to work because I see the Question form, but only the string "Answers" is displayed at the bottom of my form, not the fields.
Here is my controller action :
public function addQuestionAction(Category $category)
{
$question = new Question();
$form = $this->createForm(new QuestionType(), $question);
$request = $this->get('request');
if ($request->getMethod() === 'POST') {
$form->bind($request);
$question->setCategory($category);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($question);
$em->flush();
return $this->redirect($this->generateUrl('mycategory_questiondisplay',
array('id' => $question->getId())));
}
}
return $this->render('MyCategoryBundle:Question:add.html.twig',
array(
'form' => $form->createView(),
));
}
My QuestionType form :
<?php
namespace My\CategoryBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class QuestionType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('description')
->add('answers', 'collection', array(
'type' => new AnswerType(),
'allow_add' => true)
);
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Iel\CategoryBundle\Entity\Question'
));
}
/**
* #return string
*/
public function getName()
{
return 'my_categorybundle_question';
}
}
My Question Entity :
<?php
namespace My\CategoryBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Question
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="My\CategoryBundle\Entity\QuestionRepository")
*/
class Question
{
/**
* #ORM\OneToMany(targetEntity="My\CategoryBundle\Entity\Answer",
mappedBy="question", cascade={"persist", "remove"})
*/
private $answers;
public function __construct()
{
$this->answers = new
\Doctrine\Common\Collections\ArrayCollection();
}
public function addAnswer(\My\CategoryBundle\Entity\Answer
$answer)
{
$this->answers[] = $answer;
$answers->setQuestion($this);
return $this;
}
public function removeAnswer(\My\CategoryBundle\Entity\Answer $answer)
{
$this->answers->removeElement($answer);
}
public function getAnswers()
{
return $this->answers;
}
public function setAnswers($answer)
{
$this->answer = $answer;
return $this;
}
/**
* #ORM\ManyToOne(targetEntity="My\CategoryBundle\Entity\Category",
inversedBy="question")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
* })
*/
private $category;
/**
* Set category
*
#param My\CategoryBundle\Entity\Category $category
*/
public function setCategory(\My\CategoryBundle\Entity\Category $category)
{
$this->category = $category;
}
/**
* Get category
*
#return My\CategoryBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
/**
* Remove categories
**
#param My\CategoryBundle\Entity\Category $categories
*/
public function removeCategory(\My\CategoryBundle\Entity\Category $category)
{
$this->categories->removeElement($category);
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="titre", type="string", length=255)
*/
private $titre;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set titre
*
* #param string $titre
* #return Question
*/
public function setTitre($titre)
{
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* #return string
*/
public function getTitre()
{
return $this->titre;
}
/**
* Set description
*
* #param string $description
* #return Question
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
}
And finally, the Answer entity :
<?php
namespace My\CategoryBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Answer
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="My\CategoryBundle\Entity\AnswerRepository")
*/
class Answer
{
/**
* #ORM\ManyToOne(targetEntity="My\CategoryBundle\Entity\Question",
inversedBy="answer")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="question_id", referencedColumnName="id")
* })
*/
private $question;
/**
* Set question
*
#param My\CategoryBundle\Entity\Question $question
*/
public function setQuestion(\My\CategoryBundle\Entity\Question $question)
{
$this->question = $question;
}
/**
* Get question
*
#return My\CategoryBundle\Entity\Question
*/
public function getQuestion()
{
return $this->question;
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="answer", type="text", nullable=true)
*/
private $answer;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set answer
*
* #param string $answer
* #return Answer
*/
public function setAnswer($answer)
{
$this->answer = $answer;
return $this;
}
/**
* Get answer
*
* #return string
*/
public function getAnswer()
{
return $this->answer;
}
}
I'm really not able to find what's wrong in my form...
The problem is that your question does not have any answers yet. Hence no forms. Try
$question = new Question();
$question->addAnswer(new Answer());
That will show an empty answer form.
Look in the cookbook to see how to use javascript to add answers dynamically from within the browser.