I retrieved the json response of a mailjet API in $ Data
class DefaultController extends FOSRestController {
/**
* #Rest\View()
* #Rest\Get("/apitest")
*/
public function indexAction()
{
$apikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$apisecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
$mj = new \Mailjet\Client($apikey, $apisecret);
$id=17361101;
$Data = $mj->get(Resources::$Message, ['id' => $id]);
$Data= $Data->getData();
return $Data;}
The Response Json:
[{"ArrivedAt":"2016-05-13T07:34:47Z","AttachmentCount":0,"AttemptCount":0,"CampaignID":4884268551,"ContactID":1690868613,"Delay":0,"DestinationID":12344543,"FilterTime":61,"ID":17361101,"IsClickTracked":true,"IsHTMLPartIncluded":true,"IsOpenTracked":true,"IsTextPartIncluded":false,"IsUnsubTracked":false,"MessageSize":19308,"SenderID":4294850021,"SpamassassinScore":0,"SpamassRules":"","StatePermanent":false,"Status":"clicked"}]
I created an entity message containing all the attributes of the Api response
<?php
namespace DashbordMailjetBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class Message
{
/**
* #ORM\Column(type="datetime" ,name="ArrivedAt")
*/
private $ArrivedAt;
/**
* #ORM\Column(type="bigint",name="AttachmentCount")
*/
private $AttachmentCount;
/**
* #ORM\Column(type="bigint",name="AttemptCount")
*/
private $AttemptCount;
/**
* #ORM\Column(type="bigint",name="CampaignID")
*/
private $CampaignID;
/**
* #ORM\Column(type="bigint",name="ContactID")
*/
private $ContactID;
/**
* #ORM\Column(type="bigint",name="Delay")
*/
private $Delay;
/**
* #ORM\Column(type="bigint",name="DestinationID")
*/
private $DestinationID;
/**
* #ORM\Column(type="bigint",name="FilterTime")
*/
private $FilterTime;
/**
* #var bigint $uid
*
* #ORM\Column(name="id", type="bigint", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $ID;
/**
* #ORM\Column(type="boolean",name="IsClickTracked")
*/
private $IsClickTracked;
/**
* #ORM\Column(type="boolean",name="IsHTMLPartIncluded")
*/
private $IsHTMLPartIncluded;
/**
* #ORM\Column(type="boolean",name="IsOpenTracked")
*/
private $IsOpenTracked;
/**
* #var boolean
*
* #ORM\Column(type="boolean",name="IsTextPartIncluded")
*/
private $IsTextPartIncluded;
/**
* #ORM\Column(type="boolean",name="IsUnsubTracked")
*/
private $IsUnsubTracked;
/**
* #ORM\Column(type="bigint",name="MessageSize")
*/
private $MessageSize;
/**
* #ORM\Column(type="bigint",name="SenderID")
*/
private $SenderID;
/**
* #ORM\Column(type="string",name="SpamassassinScore")
*/
private $SpamassassinScore;
/**
* #ORM\Column(type="string",name="SpamassRules", nullable=true)
*/
private $SpamassRules;
/**
* #ORM\Column(type="boolean",name="StatePermanent")
*/
private $StatePermanent;
/**
* #ORM\Column(type="string",name="Status")
*/
private $Status;
/**
* #return datetime
*/
public function getArrivedAt()
{
return $this->ArrivedAt;
}
/**
* #param datetime $ArrivedAt
*/
public function setArrivedAt($ArrivedAt)
{
$this->ArrivedAt = $ArrivedAt;
}
/**
* #return mixed
*/
public function getAttachmentCount()
{
return $this->AttachmentCount;
}
/**
* #param mixed $AttachmentCount
*/
public function setAttachmentCount($AttachmentCount)
{
$this->AttachmentCount = $AttachmentCount;
}
/**
* #return int
*/
public function getAttemptCount()
{
return $this->AttemptCount;
}
/**
* #param int $AttemptCount
*/
public function setAttemptCount($AttemptCount)
{
$this->AttemptCount = $AttemptCount;
}
/**
* #return int
*/
public function getCampaignID()
{
return $this->CampaignID;
}
/**
* #param int $CampaignID
*/
public function setCampaignID($CampaignID)
{
$this->CampaignID = $CampaignID;
}
/**
* #return int
*/
public function getContactID()
{
return $this->ContactID;
}
/**
* #param int $ContactID
*/
public function setContactID($ContactID)
{
$this->ContactID = $ContactID;
}
/**
* #return int
*/
public function getDelay()
{
return $this->Delay;
}
/**
* #param int $Delay
*/
public function setDelay($Delay)
{
$this->Delay = $Delay;
}
/**
* #return int
*/
public function getDestinationID()
{
return $this->DestinationID;
}
/**
* #param int $DestinationID
*/
public function setDestinationID($DestinationID)
{
$this->DestinationID = $DestinationID;
}
/**
* #return int
*/
public function getFilterTime()
{
return $this->FilterTime;
}
/**
* #param int $FilterTime
*/
public function setFilterTime($FilterTime)
{
$this->FilterTime = $FilterTime;
}
/**
* #return mixed
*/
public function getID()
{
return $this->ID;
}
/**
* #param mixed $ID
*/
public function setID($ID)
{
$this->ID = $ID;
}
/**
* #return boolean
*/
public function isIsClickTracked()
{
return $this->IsClickTracked;
}
/**
* #param boolean $IsClickTracked
*/
public function setIsClickTracked($IsClickTracked)
{
$this->IsClickTracked = $IsClickTracked;
}
/**
* #return boolean
*/
public function isIsHTMLPartIncluded()
{
return $this->IsHTMLPartIncluded;
}
/**
* #param boolean $IsHTMLPartIncluded
*/
public function setIsHTMLPartIncluded($IsHTMLPartIncluded)
{
$this->IsHTMLPartIncluded = $IsHTMLPartIncluded;
}
/**
* #return boolean
*/
public function isIsOpenTracked()
{
return $this->IsOpenTracked;
}
/**
* #param boolean $IsOpenTracked
*/
public function setIsOpenTracked($IsOpenTracked)
{
$this->IsOpenTracked = $IsOpenTracked;
}
/**
* #return boolean
*/
public function isIsTextPartIncluded()
{
return $this->IsTextPartIncluded;
}
/**
* #param boolean $IsTextPartIncluded
*/
public function setIsTextPartIncluded($IsTextPartIncluded)
{
$this->IsTextPartIncluded = $IsTextPartIncluded;
}
/**
* #return boolean
*/
public function isIsUnsubTracked()
{
return $this->IsUnsubTracked;
}
/**
* #param boolean $IsUnsubTracked
*/
public function setIsUnsubTracked($IsUnsubTracked)
{
$this->IsUnsubTracked = $IsUnsubTracked;
}
/**
* #return int
*/
public function getMessageSize()
{
return $this->MessageSize;
}
/**
* #param int $MessageSize
*/
public function setMessageSize($MessageSize)
{
$this->MessageSize = $MessageSize;
}
/**
* #return int
*/
public function getSenderID()
{
return $this->SenderID;
}
/**
* #param int $SenderID
*/
public function setSenderID($SenderID)
{
$this->SenderID = $SenderID;
}
/**
* #return string
*/
public function getSpamassassinScore()
{
return $this->SpamassassinScore;
}
/**
* #param string $SpamassassinScore
*/
public function setSpamassassinScore($SpamassassinScore)
{
$this->SpamassassinScore = $SpamassassinScore;
}
/**
* #return string
*/
public function getSpamassRules()
{
return $this->SpamassRules;
}
/**
* #param string $SpamassRules
*/
public function setSpamassRules($SpamassRules)
{
$this->SpamassRules = $SpamassRules;
}
/**
* #return boolean
*/
public function isStatePermanent()
{
return $this->StatePermanent;
}
/**
* #param boolean $StatePermanent
*/
public function setStatePermanent($StatePermanent)
{
$this->StatePermanent = $StatePermanent;
}
/**
* #return string
*/
public function getStatus()
{
return $this->Status;
}
/**
* #param string $Status
*/
public function setStatus($Status)
{
$this->Status = $Status;
}}
I'am Trying to deserialize the api response in a message object
<?php
namespace DashbordMailjetBundle\Controller;
use DashbordMailjetBundle\Entity\Message;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use \Mailjet\Resources;
use JMS\Serializer\SerializerBuilder;
class DefaultController extends FOSRestController
{
/**
* #Rest\View()
* #Rest\Get("/apitest")
*/
public function indexAction()
{
$apikey = 'xxxxxxxxxxxxxxxxxxxx';
$apisecret = 'xxxxxxxxxxxxxxxxxxxxx';
$mj = new \Mailjet\Client($apikey, $apisecret);
$id=17361101;
$Data = $mj->get(Resources::$Message, ['id' => $id]);
$Data= $Data->getData();
$serializer = SerializerBuilder::create()->build();
$msg=$serializer->deserialize($Data, 'DashbordMailjetBundle\Entity \Message', 'json');
$em = $this->getDoctrine()->getManager();
$em->persist($msg);
return $msg;
}
But I have this error : Warning: json_decode() expects parameter 1 to be string, array given, Any help ?
{"error":{"code":500,"message":"Internal Server Error","exception": [{"message":"Warning: json_decode() expects parameter 1 to be string, array given","class":"Symfony\\Component\\Debug\\Exception\\ContextErrorException","trace":[{"namespace":"","short_class":"","class":"","type":"","function":"","file":"\/home\/chayma\/my_project_name\/vendor\/jms\/serializer\/src\/JMS\/Serializer\/JsonDeserializationVisitor.php","line":27,"args":[]},{"namespace":"Symfony\\Component\\Debug","short_class":"ErrorHandler","class":"Symfony\\Component\\Debug\\ErrorHandler","type":"->","function":"handleError","file":null,"line":null,"args":[["string","2"],["string","json_decode() expects parameter 1 to be string, array given"],["string","\/home\/chayma\/my_project_name\/vendor\/jms\/serializer\/src\/JMS\/Serializer\/JsonDeserializationVisitor.php"],["string","27"],["array",{"str":["array",[["array",{"ArrivedAt":["string","2016-05-13T07:34:47Z"],"AttachmentCount":["string","0"],"AttemptCount":["string","0"],"CampaignID":["string","4884268551"],"ContactID":["string","1690868613"],"Delay":["string","0"],"DestinationID":["string","12344543"],"FilterTime":["string","61"],"ID":["string","17361101"],"IsClickTracked":["boolean",true],"IsHTMLPartIncluded":["boolean",true],"IsOpenTracked":["boolean",true],"IsTextPartIncluded":["boolean",false],"IsUnsubTracked":["boolean",false],"MessageSize":["string","19308"],"SenderID":["string","4294850021"],"SpamassassinScore":["string","0"],"SpamassRules":["string",""],"StatePermanent":["boolean",false],"Status":["string","clicked"]}]]]}]]},
As said supra, the serializer is expecting a string, but, if I print the result of $Data->getData(), I get an array, such as the one below:
Array
(
[0] => Array
(
[ArrivedAt] => 2017-02-15T10:01:00Z
[AttachmentCount] => 0
[AttemptCount] => 0
[CampaignID] => 5946xxxxxx
[ContactID] => 1725xxxxxx
[Delay] => 0
[DestinationID] => 14
[FilterTime] => 111
[ID] => 16888626888xxxxxx
[IsClickTracked] =>
[IsHTMLPartIncluded] => 1
[IsOpenTracked] => 1
[IsTextPartIncluded] => 1
[IsUnsubTracked] =>
[MessageSize] => 2213
[SenderID] => 4863xxxxxx
[SpamassassinScore] => 0
[SpamassRules] =>
[StatePermanent] =>
[Status] => opened
)
)
I'd advise you to look at the repository of the PHP wrapper, or at the documentation for PHP users.
hAPI coding!
Disclaimer: Mailjet's employee here.
As defined in the serializer documentation, $serializer->deserialize() expects a string.
It seems that your $Data->getData(); returns an array. (that's what the error message is telling you ;D )
Related
Users Entity :
<?php
namespace App\Entity;
use App\Entity;
use Doctrine\ORM\Mapping;
/**
* #Entity
* #Table(name="users", options={"collate":"utf8_general_ci", "charset":"utf8", "engine":"MyISAM"})
*/
class Users extends Entity {
/**
* #Column(type="string", length=50)
* #var string
*/
protected $email;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $encrypted_password;
/**
* #Column(type="string", length=10)
* #var string
*/
protected $salt;
/**
* #Column(type="smallint", options={"default":"0","comment":"0 : Doctor, 1 : Assistant, 2 : Student"}))
* #var smallint
*/
protected $type;
/**
* #Column(type="string", length=150)
* #var string
*/
protected $sef_link;
/**
* #return string
*/
public function getEmail() {
return $this->email;
}
/**
* #param string $email
*/
public function setEmail($email) {
$this->email = $email;
}
/**
* #return string
*/
public function getEncryptedPassword() {
return $this->encrypted_password;
}
/**
* #param string $encrypted_password
*/
public function setEncryptedPassword($encrypted_password) {
$this->encrypted_password = $encrypted_password;
}
/**
* #return string
*/
public function getSalt() {
return $this->salt;
}
/**
* #param string $salt
*/
public function setSalt($salt) {
$this->salt = $salt;
}
/**
* #return integer
*/
public function getType() {
return $this->type;
}
/**
* #param integer $type
*/
public function setType($type) {
$this->type = $type;
}
/**
* #return string
*/
public function getSefLink() {
return $this->sef_link;
}
/**
* #param string $sef_link
*/
public function setSefLink($sef_link) {
$this->sef_link = $sef_link;
}
}
UserInformation Entity :
<?php
namespace App\Entity;
use App\Entity;
use Doctrine\ORM\Mapping;
/**
* #Entity
* #Table(name="user_information", options={"collate":"utf8_general_ci", "charset":"utf8", "engine":"MyISAM"})
*/
class UserInformation extends Entity {
/**
* #Column(type="integer", unique=true)
* #var integer
*/
protected $uid;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $title;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $name;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $surname;
/**
* #Column(type="date", nullable=true)
* #var date
*/
protected $born;
/**
* #Column(type="text", length=65532)
* #var text
*/
protected $address;
/**
* #Column(type="string", length=100)
* #var string
*/
protected $cv_path;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $facebook_link;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $twitter_link;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $instagram_link;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $linkedin_link;
/**
* #Column(type="string", length=100)
* #var string
*/
protected $img_path;
/**
* #Column(type="date", nullable=true)
* #var date
*/
protected $university_graduated_at;
/**
* #Column(type="date", nullable=true)
* #var date
*/
protected $md_graduated_at;
/**
* #Column(type="date", nullable=true)
* #var date
*/
protected $associate_professor_graduated_at;
/**
* #return int
*/
public function getUid() {
return $this->uid;
}
/**
* #param int $uid
*/
public function setUid($uid) {
$this->uid = $uid;
}
/**
* #return string
*/
public function getTitle() {
return $this->title;
}
/**
* #param string $title
*/
public function setTitle($title) {
$this->title = $title;
}
/**
* #return string
*/
public function getName() {
return $this->name;
}
/**
* #param string $name
*/
public function setName($name) {
$this->name = $name;
}
/**
* #return string
*/
public function getSurname() {
return $this->surname;
}
/**
* #param string $surname
*/
public function setSurname($surname) {
$this->surname = $surname;
}
/**
* #return date
*/
public function getBorn() {
return $this->born;
}
/**
* #param date $born
*/
public function setBorn($born) {
$this->born = $born;
}
/**
* #return text
*/
public function getAddress() {
return $this->address;
}
/**
* #param text $address
*/
public function setAddress($address) {
$this->address = $address;
}
/**
* #return string
*/
public function getCvPath() {
return $this->cv_path;
}
/**
* #param string $cv_path
*/
public function setCvPath($cv_path) {
$this->cv_path = $cv_path;
}
/**
* #return string
*/
public function getFacebookLink() {
return $this->facebook_link;
}
/**
* #param string $facebook_link
*/
public function setFacebookLink($facebook_link) {
$this->facebook_link = $facebook_link;
}
/**
* #return string
*/
public function getTwitterLink() {
return $this->twitter_link;
}
/**
* #param string $twitter_link
*/
public function setTwitterLink($twitter_link) {
$this->twitter_link = $twitter_link;
}
/**
* #return string
*/
public function getInstagramLink() {
return $this->instagram_link;
}
/**
* #param string $instagram_link
*/
public function setInstagramLink($instagram_link) {
$this->instagram_link = $instagram_link;
}
/**
* #return string
*/
public function getLinkedinLink() {
return $this->linkedin_link;
}
/**
* #param string $linkedin_link
*/
public function setLinkedinLink($linkedin_link) {
$this->linkedin_link = $linkedin_link;
}
/**
* #return string
*/
public function getImgPath() {
return $this->img_path;
}
/**
* #param string $img_path
*/
public function setImgPath($img_path) {
$this->img_path = $img_path;
}
/**
* #return date
*/
public function getUniversityGraduatedAt() {
return $this->university_graduated_at;
}
/**
* #param date $university_graduated_at
*/
public function setUniversityGraduatedAt($university_graduated_at) {
$this->university_graduated_at = $university_graduated_at;
}
/**
* #return date
*/
public function getMdGraduatedAt() {
return $this->md_graduated_at;
}
/**
* #param date $md_graduated_at
*/
public function setMdGraduatedAt($md_graduated_at) {
$this->md_graduated_at = $md_graduated_at;
}
/**
* #return date
*/
public function getAssociateProfessorGraduatedAt() {
return $this->associate_professor_graduated_at;
}
/**
* #param date $associate_professor_graduated_at
*/
public function setAssociateProfessorGraduatedAt($associate_professor_graduated_at) {
$this->associate_professor_graduated_at = $associate_professor_graduated_at;
}
}
Users Service :
public function getUserByEmailAndPassword($email, $password, $ip, $user_agent) {
$repository = $this->getEntityManager()->getRepository('App\Entity\Users');
$user = $repository->createQueryBuilder('u')->innerJoin('u.user_information', 'ui')->where('u.email = :email')->setParameter('email', $email);
I want to left join one to one users with user_information.
User Information has uid as a unique_key and refer to users id.
How can i left join and get data from user_information where uid = users id?
You have to create relation between your entities.
If you want a oneToOne relation:
class User
{
/**
* #ORM\Id
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="UserInformation")
*/
protected $userInformation;
}
class UserInformation
{
/**
* #ORM\Id
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="User", inversedBy="userInformation")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $uid;
}
Inner join:
$user = $repository
->createQueryBuilder('u')
->addSelect('ui') // to limit queries when doing $user->getUserInformation()
->innerJoin('u.userInformation', 'ui')
->where('u.email = :email')->setParameter('email', $email);
PersonneController.php
<?php
namespace biblioBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use biblioBundle\Entity\Personne;
use biblioBundle\Form\PersonneType;
/**
* Personne controller.
*
*/
class PersonneController extends Controller
{
/**
* Lists all Personne entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$personnes = $em->getRepository('biblioBundle:Personne')->findAll();
return $this->render('personne/index.html.twig', array(
'personnes' => $personnes,
));
}
/**
* Creates a new Personne entity.
*
*/
public function newAction(Request $request)
{
//$em = $this->getDoctrine()->getManager();
//$prf = $em->getRepository('biblioBundle:Profil')->findAll();
$personne = new Personne();
$form = $this->createForm(PersonneType::class, $personne);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($personne);
$em->flush();
return $this->redirectToRoute('personne_show', array('id' => $personne->getIdpersonne()));
}
return $this->render('personne/new.html.twig', array(
'personne' => $personne,
'form' => $form->createView(),
));
}
PersonneType.php
<?php
namespace biblioBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use biblioBundle\Entity\Profil;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
class PersonneType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nom')
->add('prenom')
->add('datenaiss', 'date')
->add('adresse')
->add('photo1')
->add('sexe',ChoiceType::class,array(
'choices' => array(
'H' => 'Homme',
'F' => 'Femme')))
->add('idProfil',IntegerType::class);
}
/* public function getName()
{
return 'name';
}*/
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'biblioBundle\Entity\Personne'
));
}
}
Personne.php
<?php
namespace biblioBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Personne
*
* #ORM\Table(name="personne", indexes= {#ORM\Index(name="FK_Appartenir2", columns={"idProfil"})})
* #ORM\Entity
*/
class Personne
{
/**
* #var string
*
* #ORM\Column(name="Nom", type="string", length=20, nullable=false)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="Prenom", type="string", length=20, nullable=false)
*/
private $prenom;
/**
* #var \DateTime
*
* #ORM\Column(name="DateNaiss", type="date", nullable=false)
*/
private $datenaiss;
/**
* #var string
*
* #ORM\Column(name="Adresse", type="string", length=100, nullable=true)
*/
private $adresse;
/**
* #var string
*
* #ORM\Column(name="Photo1", type="string", length=255, nullable=true)
*/
private $photo1;
/**
* #var string
*
* #ORM\Column(name="Sexe", type="string", length=1, nullable=false)
*/
private $sexe;
/**
* #var integer
*
* #ORM\Column(name="idPersonne", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idpersonne;
/**
* #var \biblioBundle\Entity\Profil
*
* #ORM\ManyToOne(targetEntity="biblioBundle\Entity\Profil")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="idProfil", referencedColumnName="idProfil")
* })
*/
private $idprofil;
/**
* Set nom
*
* #param string $nom
* #return Personne
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set prenom
*
* #param string $prenom
* #return Personne
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get prenom
*
* #return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set datenaiss
*
* #param \DateTime $datenaiss
* #return Personne
*/
public function setDatenaiss($datenaiss)
{
$this->datenaiss = $datenaiss;
return $this;
}
/**
* Get datenaiss
*
* #return \DateTime
*/
public function getDatenaiss()
{
return $this->datenaiss;
}
/**
* Set adresse
*
* #param string $adresse
* #return Personne
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* #return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set photo1
*
* #param string $photo1
* #return Personne
*/
public function setPhoto1($photo1)
{
$this->photo1 = $photo1;
return $this;
}
/**
* Get photo1
*
* #return string
*/
public function getPhoto1()
{
return $this->photo1;
}
/**
* Set sexe
*
* #param string $sexe
* #return Personne
*/
public function setSexe($sexe)
{
$this->sexe = $sexe;
return $this;
}
/**
* Get sexe
*
* #return string
*/
public function getSexe()
{
return $this->sexe;
}
/**
* Get idpersonne
*
* #return integer
*/
public function getIdpersonne()
{
return $this->idpersonne;
}
/**
* Set idprofil
*
* #param \biblioBundle\Entity\Profil $idprofil
* #return Personne
*/
public function setIdprofil(\biblioBundle\Entity\Profil $idprofil = null)
{
$this->idprofil = $idprofil;
return $this;
}
/**
* Get idprofil
*
* #return \biblioBundle\Entity\Profil
*/
public function getIdprofil()
{
return $this->idprofil;
}
}
Every time I try to run the code I get:
{Expected argument of type "biblioBundle\Entity\Profil", "integer" given }
Please I need help.
In your PersonneType class you have line:
->add('idProfil',IntegerType::class);
when in Personne class you have:
public function setIdprofil(\biblioBundle\Entity\Profil $idprofil = null)
{
$this->idprofil = $idprofil;
return $this;
}
You need to have Profil instance instead of integer (defined in form). How to solve this?
Replace IntegerType class to EntityType.
Add data transformer to form and transform integer to Profil and vice versa.
Replace argument $idprofil with integer type instead of Profil.
I have a problem implementing a symfony 3 form with two objects having a many-to-many relationship.
I have two datatables, "Users" and "Roles". I want to have a form, where I can edit a user and assign a user some roles. In detail I want a form where each Role is a checkbox and I can choose which role a user has.
I know, that I have to implement a new UserType,, but how can I implement the dynamic checkboxes?
This is my User-Class:
<?php
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Table(name="app_users")
* #ORM\Entity(repositoryClass="AppBundle\Entity\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
* #ORM\JoinTable(name="user_roles")
*/
private $roles;
public function __construct()
{
$this->isActive = true;
// may not be needed, see section on salt below
// $this->salt = md5(uniqid(null, true));
}
public function getUsername()
{
return $this->username;
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
$permissionsArray = array();
foreach ($this->roles as $role)
{
$rolesPermissions = $role->getPermissions();
for($i=0;$i<count($rolesPermissions);$i++)
if(!in_array($rolesPermissions[$i],$permissionsArray))
$permissionsArray[] = $rolesPermissions[$i];
}
return $permissionsArray;
}
public function eraseCredentials()
{
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
*
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Set email
*
* #param string $email
*
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set isActive
*
* #param boolean $isActive
*
* #return User
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
}
And this is my Role-Class:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Role
*
* #ORM\Table(name="role")
* #ORM\Entity(repositoryClass="AppBundle\Repository\RoleRepository")
*/
class Role
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="bezeichnung", type="string", length=255, unique=true)
*/
private $bezeichnung;
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
/**
* #ORM\ManyToMany(targetEntity="Permission", inversedBy="roles")
* #ORM\JoinTable(name="roles_permissions")
*/
private $permissions;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set bezeichnung
*
* #param string $description
*
* #return Role
*/
public function setBezeichnung($bezeichnung)
{
$this->bezeichnung = $bezeichnung;
return $this;
}
/**
* Get bezeichnung
*
* #return string
*/
public function getBezeichnung()
{
return $this->bezeichnung;
}
/**
* Constructor
*/
public function __construct()
{
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
$this->roles = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add user
*
* #param \AppBundle\Entity\User $user
*
* #return Role
*/
public function addUser(\AppBundle\Entity\User $user)
{
$this->users[] = $user;
return $this;
}
/**
* Remove user
*
* #param \AppBundle\Entity\User $user
*/
public function removeUser(\AppBundle\Entity\User $user)
{
$this->users->removeElement($user);
}
/**
* Get users
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
/**
* Add permission
*
* #param \AppBundle\Entity\Permission $permission
*
* #return Role
*/
public function addPermission(\AppBundle\Entity\Permission $permission)
{
$this->permissions[] = $permission;
return $this;
}
/**
* Remove permission
*
* #param \AppBundle\Entity\Permission $permission
*/
public function removePermission(\AppBundle\Entity\Permission $permission)
{
$this->permissions->removeElement($permission);
}
/**
* Get permissions
*
* #return Array
*/
public function getPermissions()
{
$permissionsArray = array();
foreach ($this->permissions as $permission)
$permissionsArray[] = "ROLE_".$permission->getTechBezeichnung();
return $permissionsArray;
}
}
a) Give your entities a __toString() method.
b) Make a UserType. You can also Use the CLI command bin/console doctrine:generate:crud and choose at "write actions" [yes].
The script wil generate a controller, a formType and some templates.
c) add this use statement at the top of UserType:
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
d) add this formfield into your UserType:
->add('roles', EntityType::class, array(
'expanded => true,
'multiple' => true
))
I'm trying to send from api rest controller (Symfony3) a object collection but get an error. "{"error":{"code":500,"message":"Internal Server Error","exception":[{"message":"Notice: Undefined index: Bar"
/**
*
*
* #Get("/api/bars.{_format}", defaults={"_format"="json"}, options={"expose"=true}, name="api_bars")
* #View()
*/
public function getBarsAction (Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $this->get('Session');
$repository = $em->getRepository('AppBundle:Bar');
$bars = $repository->findAll();
foreach ($bars as $bar)
{
$id = $bar->getId();
$name = $bar->getName();
$bars[] = array('id'=>$id,'name'=>$name);
}
$view = $this->View($bars,200);
return $this->handleView($view);
}
And the Bar Entity is:
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Bar
*
* #ORM\Table(name="Bar")
* #ORM\Entity(repositoryClass="AppBundle\Repository\BarRepository")
*/
class Bar
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=45, nullable=true)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="location", type="string", length=45, nullable=true)
*/
private $location;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=45, nullable=true)
*/
private $description;
/**
* #ORM\OneToMany(targetEntity="Waiter", mappedBy="Bar")
*/
protected $waiters;
/**
* #ORM\OneToMany(targetEntity="Table_", mappedBy="Bar")
*/
protected $tables;
/** #ORM\OneToMany(targetEntity="Stock_food", mappedBy="Bar") */
private $stockfoods;
/** #ORM\OneToMany(targetEntity="Stock_drink", mappedBy="Bar") */
private $stockdrinks;
public function __construct()
{
$this->waiters = new ArrayCollection();
$this->tables = new ArrayCollection();
$this->stockfoods = new ArrayCollection();
$this->stockdrinks = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Bar
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set location
*
* #param string $location
*
* #return Bar
*/
public function setLocation($location)
{
$this->location = $location;
return $this;
}
/**
* Get location
*
* #return string
*/
public function getLocation()
{
return $this->location;
}
/**
* Set description
*
* #param string $description
*
* #return Bar
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
public function addWaiter($value){
$this->waiters[] = $value;
}
public function getWaiters(){
return $this->waiters;
}
public function removeWaiters($id)
{
//optionally add a check here to see that $group exists before removing it.
return $this->waiters->removeElement($id);
}
public function addTable($value){
$this->tables[] = $value;
}
public function getTables(){
return $this->tables;
}
public function removeTables($id)
{
//optionally add a check here to see that $group exists before removing it.
return $this->tables->removeElement($id);
}
public function addFood($value){
$this->stockfoods[] = $value;
}
public function getFoods(){
return $this->stockfoods;
}
public function removeFoods($id)
{
//optionally add a check here to see that $group exists before removing it.
return $this->stockfoods->removeElement($id);
}
public function addDrink($value){
$this->stockdrinks[] = $value;
}
public function getDrinks(){
return $this->stockdrinks;
}
public function removeDrinks($id)
{
//optionally add a check here to see that $group exists before removing it.
return $this->stockdrinks->removeElement($id);
}
}
Thanks a lot!!!!
I solved my problem!!! I was related to association mapping. I've changed this:
/**
* #ORM\OneToMany(targetEntity="Waiter", mappedBy="Bar")
*/
protected $waiters;
/**
* #ORM\OneToMany(targetEntity="Table_", mappedBy="Bar")
*/
protected $tables;
/** #ORM\OneToMany(targetEntity="Stock_food", mappedBy="Bar") */
private $stockfoods;
/** #ORM\OneToMany(targetEntity="Stock_drink", mappedBy="Bar") */
private $stockdrinks;
For this:
/**
* #ORM\OneToMany(targetEntity="Waiter", mappedBy="bar")
*/
protected $waiters;
/**
* #ORM\OneToMany(targetEntity="Table_", mappedBy="bar")
*/
protected $tables;
/** #ORM\OneToMany(targetEntity="Stock_food", mappedBy="bar") */
private $stockfoods;
/** #ORM\OneToMany(targetEntity="Stock_drink", mappedBy="bar") */
private $stockdrinks;
I have a many to many relationship using zend framework 2 and doctrine 2.
The relationship is between categories and products.
My products entity is
<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Zend\ServiceManager\ServiceManager;
use Doctrine\ORM\PersistentCollection;
use Application\Entity\Categories;
/**
* Products
*
* #ORM\Table(name="products", indexes={
* #ORM\Index(name="PRIMARY", columns={"product_id"}),
* #ORM\Index(name="created_by_user_id", columns={"created_by_user_id"}),
* #ORM\Index(name="retail_status_id", columns={"retail_status_id"}),
* })
* #ORM\Entity(repositoryClass="Application\Entity\Repository\ProductsRepository")
* #ORM\HasLifecycleCallbacks
*/
class Products extends AbstractEntity
{
/**
* #var integer
*
* #ORM\Column(name="product_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $productId;
/**
* #var \Application\Entity\AttributeSets
*
* #ORM\ManyToOne(targetEntity="Application\Entity\AttributeSets", inversedBy="products")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="attribute_set_id", referencedColumnName="attribute_set_id")
* })
*/
private $attributeSet;
/**
* #var \Application\Entity\RetailStatus
*
* #ORM\ManyToOne(targetEntity="Application\Entity\RetailStatus", inversedBy="products")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="retail_status_id", referencedColumnName="retail_status_id")
* })
*/
private $retailStatus;
/**
* #var string
*
* #ORM\Column(name="price", type="decimal", precision=9, scale=2, nullable=false)
*/
private $price;
/**
* #var integer
*
* #ORM\Column(name="active", type="integer", nullable=false)
*/
private $active;
/**
* #var \DateTime
*
* #ORM\Column(name="date_created", type="datetime")
*/
private $dateCreated;
/**
* #var \DateTime
*
* #ORM\Column(name="date_modified", type="datetime")
*/
private $dateModified;
/**
* #var \Application\Entity\Users
*
* #ORM\ManyToOne(targetEntity="Application\Entity\Users")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="created_by_user_id", referencedColumnName="user_id")
* })
*/
private $authUser;
/**
* #var \Application\Entity\ProductTitles
*
* #ORM\OneToOne(targetEntity="Application\Entity\ProductTitles", cascade={"persist", "persist"}, mappedBy="product")
*/
private $title;
/**
* #var \Application\Entity\ProductDescriptions
*
* #ORM\OneToOne(targetEntity="Application\Entity\ProductDescriptions", cascade={"persist", "persist"}, mappedBy="product")
*/
private $description;
/**
* #var \Application\Entity\ProductDimentions
*
* #ORM\OneToOne(targetEntity="Application\Entity\ProductDimentions", cascade={"persist", "persist"}, mappedBy="product")
*/
private $productDimentions;
/**
* #var \Doctrine\ORM\PersistentCollection
*
* #ORM\ManyToMany(targetEntity="Application\Entity\Categories", cascade={"persist"}, inversedBy="products")
* #ORM\JoinTable(name="product_to_catagory",
* joinColumns={#ORM\joinColumn(name="product_id", referencedColumnName="product_id")},
* inverseJoinColumns={#ORM\joinColumn(name="catagory_id", referencedColumnName="catagory_id")}
* )
*/
private $categories;
/**
* #var \Doctrine\ORM\PersistentCollection
*
* #ORM\OneToMany(targetEntity="Application\Entity\ProductAttributeValues", cascade={"persist", "persist"}, mappedBy="product")
*/
private $values;
public function __construct(ServiceManager $serviceManager = NULL)
{
parent::__construct($serviceManager);
$this->categories = new ArrayCollection();
}
/**
*
* #return integer
*/
public function getProductId()
{
return $this->productId;
}
/**
*
* #return \Application\Entity\AttributeSets
*/
public function getAttributeSet()
{
return $this->attributeSet;
}
/**
*
* #return \Application\Entity\RetailStatus
*/
public function getRetailStatus()
{
return $this->retailStatus;
}
/**
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
*
* #return boolean
*/
public function isActive()
{
return (bool) $this->active;
}
/**
*
* #return \DateTime
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
*
* #return \DateTime
*/
public function getDateModified()
{
return $this->dateModified;
}
/**
*
* #return \Application\Entity\Users
*/
public function getAuthUser()
{
return $this->authUser;
}
/**
*
* #return \Application\Entity\ProductTitles
*/
public function getTitle()
{
return $this->title;
}
/**
*
* #return \Application\Entity\ProductDescriptions
*/
public function getDescription()
{
return $this->description;
}
/**
*
* #return \Application\Entity\ProductDimentions
*/
public function getProductDimentions()
{
return $this->productDimentions;
}
/**
*
* #return \Doctrine\ORM\PersistentCollection
*/
public function getCategories()
{
return $this->categories;
}
/**
*
* #return \Doctrine\ORM\PersistentCollection
*/
public function getValues()
{
return $this->values;
}
/**
*
* #param \Application\Entity\AttributeSets $attributeSet
* #return \Application\Entity\Products
*/
public function setAttributeSet(\Application\Entity\AttributeSets $attributeSet)
{
$this->attributeSet = $attributeSet;
return $this;
}
/**
*
* #param \Application\Entity\RetailStatus $retailStatus
* #return \Application\Entity\Products
*/
public function setRetailStatus(\Application\Entity\RetailStatus $retailStatus)
{
$this->retailStatus = $retailStatus;
return $this;
}
/**
*
* #param string $price
* #return \Application\Entity\Products
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
*
* #param integer $active
* #return \Application\Entity\Products
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
/**
*
* #param \DateTime $dateCreated
* #return \Application\Entity\Products
*/
public function setDateCreated(\DateTime $dateCreated)
{
$this->dateCreated = $dateCreated;
return $this;
}
/**
*
* #param \DateTime $dateModified
* #return \Application\Entity\Products
*/
public function setDateModified(\DateTime $dateModified)
{
$this->dateModified = $dateModified;
return $this;
}
/**
*
* #param \Application\Entity\Users $authUser
* #return \Application\Entity\Products
*/
public function setAuthUser(\Application\Entity\Users $authUser)
{
$this->authUser = $authUser;
return $this;
}
/**
*
* #param \Application\Entity\ProductTitles $title
* #return \Application\Entity\Products
*/
public function setTitle(\Application\Entity\ProductTitles $title)
{
$this->title = $title;
return $this;
}
/**
*
* #param \Application\Entity\ProductDescriptions $description
* #return \Application\Entity\Products
*/
public function setDescription(\Application\Entity\ProductDescriptions $description)
{
$this->description = $description;
return $this;
}
/**
*
* #param \Application\Entity\ProductDimentions $productDimentions
* #return \Application\Entity\Products
*/
public function setProductDimentions(\Application\Entity\ProductDimentions $productDimentions)
{
$this->productDimentions = $productDimentions;
return $this;
}
public function addCategory(Categories $category)
{
$this->categories->add($category);
}
/**
*
* #param \Doctrine\Common\Collections\ArrayCollection $categories
* #return \Application\Entity\Products
*/
public function addCategories(\Doctrine\Common\Collections\ArrayCollection $categories)
{
foreach ($categories as $category) {
$this->addCategory($category);
}
// \Freedom\Logger\InfoLogger::vardump($this->categories);
return $this;
}
public function removeCategories(\Doctrine\Common\Collections\ArrayCollection $categories)
{
foreach ($categories as $category) {
$this->categories->removeElement($category);
}
return $this;
}
/**
* #ORM\PrePersist
* #return \Application\Entity\Users
*/
public function prePersist()
{
$this->dateCreated = $this->getCurrentDateTime();
$this->dateModified = $this->getCurrentDateTime();
$this->authUser = $this->getAutherizedUser();
// $this->categories = new PersistentCollection($this->getEntityManager(), NULL, $this->categories);
// \Freedom\Logger\InfoLogger::vardump($this->categories->count());
// \Freedom\Logger\InfoLogger::vardump($this->categories);
return $this;
}
/**
* #ORM\PreUpdate
* #return \Application\Entity\Users
*/
public function preUpdate()
{
// $this->dateModified = $this->getCurrentDateTime();
return $this;
}
public function toArray()
{
$array = array();
foreach (get_object_vars($this) as $var => $value) {
switch ($var) {
case 'authUser':
if (!is_null($value)) {
$array[$var] = $value->toArray();
}
break;
default:
$array[$var] = $value;
}
}
return $array;
}
}
and my category entity
<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\ServiceManager\ServiceManager;
use Application\Entity\StaticPages;
/**
* Categories
*
* #ORM\Table(name="catagories", indexes={
* #ORM\Index(name="PRIMARY", columns={"catagory_id"}),
* #ORM\Index(name="created_by_user_id", columns={"created_by_user_id"}),
* })
* #ORM\Entity(repositoryClass="Application\Entity\Repository\CategoriesRepository")
* #ORM\HasLifecycleCallbacks
*/
class Categories extends AbstractEntity
{
/**
* #var integer
*
* #ORM\Column(name="catagory_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $catagoryId;
/**
* #var string
*
* #ORM\Column(name="category", type="string", length=30, nullable=false)
*/
private $category;
/**
* #var \DateTime
*
* #ORM\Column(name="date_created", type="datetime")
*/
private $dateCreated;
/**
* #var \DateTime
*
* #ORM\Column(name="date_modified", type="datetime")
*/
private $dateModified;
/**
* #var \Application\Entity\Users
*
* #ORM\ManyToOne(targetEntity="Application\Entity\Users")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="created_by_user_id", referencedColumnName="user_id")
* })
*/
private $authUser;
/**
* #var \Application\Entity\Categories
*
* #ORM\ManyToOne(targetEntity="Application\Entity\Categories", inversedBy="childCategories")
* #ORM\JoinColumn(name="parent_catagory_id", referencedColumnName="catagory_id")
*/
protected $parentCategory;
/**
* #var \Doctrine\ORM\PersistentCollection
*
* #ORM\OneToMany(targetEntity="Application\Entity\Categories", mappedBy="parentCategory")
*/
protected $childCategories;
/**
* #var Doctrine\ORM\PersistentCollection
*
* #ORM\ManyToMany(targetEntity="Application\Entity\Products", cascade={"persist"}, orphanRemoval=true, mappedBy="categories")
*/
private $products;
/**
* #var \Application\Entity\Sites
*
* #ORM\ManyToOne(targetEntity="Application\Entity\Sites", inversedBy="categories")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="site_id", referencedColumnName="site_id")
* })
*/
private $site;
/**
* #var \Application\Entity\StaticPages
*
* #ORM\OneToOne(targetEntity="Application\Entity\StaticPages", mappedBy="category", cascade="persist")
*/
private $staticPage;
/**
* #var integer
*
* #ORM\Column(name="active", type="integer", nullable=false)
*/
private $active;
/**
* #var string
*
* #ORM\Column(name="url_key", type="string", length=30, nullable=false)
*/
private $urlKey;
/**
* #var string
*
* #ORM\Column(name="description", type="text", length=200, nullable=false)
*/
private $description;
/**
* #var integer
*
* #ORM\Column(name="sort_order", type="integer", nullable=false)
*/
private $sortOrder;
public function __construct(ServiceManager $serviceManager = NULL)
{
parent::__construct($serviceManager);
$this->parentCategory = NULL;
$this->urlKey = NULL;
}
/**
*
* #return integer
*/
public function getCatagoryId()
{
return $this->catagoryId;
}
/**
*
* #return string
*/
public function getCategory()
{
return $this->category;
}
/**
*
* #return \DateTime
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
*
* #return \DateTime
*/
public function getDateModified()
{
return $this->dateModified;
}
/**
*
* #return \Application\Entity\Users
*/
public function getAuthUser()
{
return $this->authUser;
}
/**
*
* #return boolean
*/
public function hasChildCategories()
{
return (bool) $this->getChildCategories()->count();
}
/**
*
* #return \Doctrine\ORM\PersistentCollection
*/
public function getChildCategories()
{
return $this->childCategories;
}
/**
*
* #return boolean
*/
public function hasParentCategory()
{
return (bool) $this->getParentCategory();
}
/**
*
* #return \Application\Entity\Categories
*/
public function getParentCategory()
{
return $this->parentCategory;
}
public function hasProducts()
{
return (bool) $this->getProducts()->count();
}
/**
*
* #return \Doctrine\ORM\PersistentCollection
*/
public function getProducts()
{
return $this->products;
}
/**
*
* #return \Application\Entity\Sites
*/
public function getSite()
{
return $this->site;
}
/**
*
* #return \Application\Entity\StaticPages
*/
public function getStaticPage()
{
return $this->staticPage;
}
/**
*
* #return boolean
*/
public function isActive()
{
return (bool) $this->active;
}
/**
*
* #return strng
*/
public function getUrlKey()
{
return $this->urlKey;
}
/**
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
*
* #return integer
*/
public function getSortOrder()
{
return $this->sortOrder;
}
/**
*
* #param string $category
* #return \Application\Entity\Categories
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
*
* #param \DateTime $dateCreated
* #return \Application\Entity\Categories
*/
public function setDateCreated(\DateTime $dateCreated)
{
$this->dateCreated = $dateCreated;
return $this;
}
/**
*
* #param \DateTime $dateModified
* #return \Application\Entity\Categories
*/
public function setDateModified(\DateTime $dateModified)
{
$this->dateModified = $dateModified;
return $this;
}
/**
*
* #param \Application\Entity\Sites $site
* #return \Application\Entity\Categories
*/
public function setSite(\Application\Entity\Sites $site)
{
$this->site = $site;
return $this;
}
public function hasStaticPage()
{
return (bool) $this->getStaticPage();
}
/**
*
* #param \Application\Entity\StaticPages $staticPage
* #return \Application\Entity\Categories
*/
public function setStaticPage(\Application\Entity\StaticPages $staticPage)
{
$this->staticPage = $staticPage;
return $this;
}
public function removeStaticPage()
{
if ($this->getStaticPage() instanceof StaticPages) {
$entityManager = $this->getEntityManager();
$entityManager->remove($this->staticPage);
$entityManager->flush();
}
$this->staticPage = NULL;
}
/**
*
* #param \Application\Entity\Users $authUser
* #return \Application\Entity\Categories
*/
public function setAuthUser(\Application\Entity\Users $authUser)
{
$this->authUser = $authUser;
return $this;
}
/**
*
* #param \Application\Entity\Categories $parentCategory
* #return \Application\Entity\Categories
*/
public function setParentCategory(\Application\Entity\Categories $parentCategory)
{
$this->parentCategory = $parentCategory;
return $this;
}
/**
*
* #param integer $active
* #return \Application\Entity\Categories
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
/**
*
* #param string $urlKey
* #return \Application\Entity\Categories
*/
public function setUrlKey($urlKey)
{
$escapeUri = $this->getServiceManager()->get('ViewHelperManager')->get('escapeUrl');
$this->urlKey = $escapeUri($urlKey);
return $this;
}
/**
*
* #param string $description
* #return \Application\Entity\Categories
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
*
* #param integer $sortOrder
* #return \Application\Entity\Categories
*/
public function setSortOrder($sortOrder)
{
$this->sortOrder = $sortOrder;
return $this;
}
/**
* #ORM\PrePersist
* #return \Application\Entity\Users
*/
public function prePersist()
{
$this->dateCreated = $this->getCurrentDateTime();
$this->dateModified = $this->getCurrentDateTime();
$this->authUser = $this->getAutherizedUser();
return $this;
}
/**
* #ORM\PreUpdate
* #return \Application\Entity\Users
*/
public function preUpdate()
{
$this->dateModified = $this->getCurrentDateTime();
return $this;
}
public function toArray()
{
$array = array();
foreach (get_object_vars($this) as $var => $value) {
switch ($var) {
case 'products':
foreach ($value as $product) {
$array[$var][] = $product->toArray();
}
break;
case 'authUser':
if (!is_null($value)) {
$array[$var] = $value->toArray();
}
break;
default:
$array[$var] = $value;
}
}
return $array;
}
}
As can be seen the products and categories are linked through the table product_to_catagory.
I am using doctrines object multi checkbox to get the categories for the product using
$this->add(array(
'name' => 'categories',
'type' => 'Admin\DoctrineModule\Form\Element\ObjectMultiCheckbox',
'options' => array(
'label' => _('Categories:'),
'label_attributes' => array('class' => 'required'),
'object_manager' => $this->getEntityManager(),
'target_class' => 'Application\Entity\Categories',
'property' => 'category',
'is_method' => true,
'find_method' => array(
'name' => 'FindAll',
),
'disable_inarray_validator' => true,
),
));
The form is bound to the products entity
After the form is submitted the categories in the product entity returns Doctrine\Common\Collections\ArrayCollection
The problem I am having is that the categories are not being saved on the database in the product_to_catagory table when I flush the products entity.
Does anyone know what I am doing wrong?
Many thanks in advance.
EDIT
Changed owning side to products, code above updated.