symfony2,doctrine2,entity , Doctrine persist entity with inverse relation not work


Doctrine persist entity with inverse relation not work

Question:

Tag: symfony2,doctrine2,entity

I'm trying to save two entities linked. Product entity may have any or many entities ProviderRate. When I try to save the product entity, it tells me that ProviderRate related entity has not assigned one of their required fields. I need to save a product with no need to assign a ProviderRate.

The error message showing me is:

Entity of type AppBundle\Entity\ProviderRate is missing an assigned ID for field 'provider'.
The identifier generation strategy for this entity requires the ID field to be populated before EntityManager#persist() is called.
If you want automatically generated identifiers instead you need to adjust the metadata mapping accordingly.

My entitdades code is as follows:

Product Entity

 /**
    * Products
     *
         * @ORM\Table(name="products", uniqueConstraints={@ORM\UniqueConstraint(name="id_producto_UNIQUE", columns={"id"})}, indexes={@ORM\Index(name="fk_id_productos_id_categorias1_idx", columns={"category_id"}), @ORM\Index(name="fk_id_productos_id_producto_tipo1_idx", columns={"type"}), @ORM\Index(name="fk_id_productos_id_moneda1_idx", columns={"currency_id"})})
         * @ORM\Entity(repositoryClass="AppBundle\Repository\ProductsRepository")
         */
        class Products {
            /**
         * @var string
         *
         * @ORM\Column(name="name", type="string", length=45, nullable=false)
         * @Assert\NotBlank(message="Por favor, escriba el nombre del producto.")
         */
        private $name;

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

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

        /**
         * @var string
         *
         * @ORM\Column(name="description_long", type="text", nullable=false)
         */
        private $descriptionLong;

        /**
         * @var integer
         *
         * @ORM\Column(name="amount_per_unit", type="integer", nullable=false)
         */
        private $amountPerUnit;

        /**
         * @var string
         *
         * @ORM\Column(name="weight", type="decimal", precision=11, scale=3, nullable=false)
         */
        private $weight;

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

        /**
         * @var boolean
         *
         * @ORM\Column(name="isActive", type="boolean", nullable=false)
         */
        private $isactive;

        /**
         * @var \DateTime
         *
         * @ORM\Column(name="createdtime", type="datetime", nullable=false)
         * @Assert\DateTime()
         */
        private $createdtime;

        /**
         * @var \DateTime
         *
         * @ORM\Column(name="modifiedtime", type="datetime", nullable=false)
         * @Assert\DateTime()
         */
        private $modifiedtime;

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

        /**
         * @var boolean
         *
         * @ORM\Column(name="isDeleted", type="boolean", nullable=false)
         */
        private $isdeleted;

        /**
         * @var integer
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="IDENTITY")
         */
        private $id;

        /**
         * @var \AppBundle\Entity\Categories
         *
         * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Categories")
         * @ORM\JoinColumns({
         *   @ORM\JoinColumn(name="category_id", referencedColumnName="id")
         * })
         */
        private $category;

        /**
         * @var \AppBundle\Entity\ProductTypes
         *
         * @ORM\ManyToOne(targetEntity="AppBundle\Entity\ProductTypes")
         * @ORM\JoinColumns({
         *   @ORM\JoinColumn(name="type", referencedColumnName="id")
         * })
         */
        private $type;

        /**
         * @var \AppBundle\Entity\Currencies
         *
         * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Currencies")
         * @ORM\JoinColumns({
         *   @ORM\JoinColumn(name="currency_id", referencedColumnName="id")
         * })
         */
        private $currency;

        /**
         * @var \Doctrine\Common\Collections\Collection
         *
         * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Sets", inversedBy="product")
         * @ORM\JoinTable(name="products_sets",
         *   joinColumns={
         *     @ORM\JoinColumn(name="product_id", referencedColumnName="id")
         *   },
         *   inverseJoinColumns={
         *     @ORM\JoinColumn(name="set_id", referencedColumnName="id")
         *   }
         * )
         */
        private $set;

        /**
         * @var \Doctrine\Common\Collections\Collection
         *
         * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Products", mappedBy="productParentid")
         */
        private $product;

        /**
         * @var \Doctrine\Common\Collections\Collection
         *
         * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Documents", inversedBy="product")
         * @ORM\JoinTable(name="product_attachments",
         *   joinColumns={
         *     @ORM\JoinColumn(name="product_id", referencedColumnName="id")
         *   },
         *   inverseJoinColumns={
         *     @ORM\JoinColumn(name="document_id", referencedColumnName="id")
         *   }
         * )
         */
        private $document;

        /**
         * @var \Doctrine\Common\Collections\Collection
         *
         * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Images", inversedBy="product")
         * @ORM\JoinTable(name="products_images",
         *   joinColumns={
         *     @ORM\JoinColumn(name="product_id", referencedColumnName="id")
         *   },
         *   inverseJoinColumns={
         *     @ORM\JoinColumn(name="image_id", referencedColumnName="id")
         *   }
         * )
         */
        private $image;

        // CUSTOM CODE
        /** 
         * @ORM\OneToMany(targetEntity="AppBundle\Entity\ProviderRate", mappedBy="product", cascade={"persist"})
         */
        private $providerRate;

        /**
         * Constructor
         */
        public function __construct() {
            $this->createdtime      = new \DateTime();
            $this->modifiedtime     = new \DateTime();
            $this->set              = new \Doctrine\Common\Collections\ArrayCollection();
            $this->product          = new \Doctrine\Common\Collections\ArrayCollection();
            $this->document         = new \Doctrine\Common\Collections\ArrayCollection();
            $this->image            = new \Doctrine\Common\Collections\ArrayCollection();
            $this->providerRate     = new \Doctrine\Common\Collections\ArrayCollection();
            $this->descriptionLong  = '';
            $this->amountPerUnit    = 1;
            $this->web              = '';
            $this->weight           = 0;
            $this->isdeleted        = 0;
        }


        /**
         * Set name
         *
         * @param string $name
         * @return Products
         */
        public function setName($name) {
            $this->name = $name;

            return $this;
        }

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

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

            return $this;
        }

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

        /**
         * Set code
         *
         * @param string $code
         * @return Products
         */
        public function setCode($code) {
            $this->code = $code;

            return $this;
        }

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

        /**
         * Set descriptionLong
         *
         * @param string $descriptionLong
         * @return Products
         */
        public function setDescriptionLong($descriptionLong) {
            $this->descriptionLong = $descriptionLong;

            return $this;
        }

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

        /**
         * Set amountPerUnit
         *
         * @param integer $amountPerUnit
         * @return Products
         */
        public function setAmountPerUnit($amountPerUnit) {
            $this->amountPerUnit = $amountPerUnit;

            return $this;
        }

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

        /**
         * Set weight
         *
         * @param string $weight
         * @return Products
         */
        public function setWeight($weight) {
            $this->weight = $weight;

            return $this;
        }

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

        /**
         * Set web
         *
         * @param string $web
         * @return Products
         */
        public function setWeb($web) {
            $this->web = $web;

            return $this;
        }

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

        /**
         * Set isactive
         *
         * @param boolean $isactive
         * @return Products
         */
        public function setIsactive($isactive) {
            $this->isactive = $isactive;

            return $this;
        }

        /**
         * Get isactive
         *
         * @return boolean 
         */
        public function getIsactive() {
            return $this->isactive;
        }

        /**
         * Set createdtime
         *
         * @param \DateTime $createdtime
         * @return Products
         */
        public function setCreatedtime($createdtime) {
            $this->createdtime = $createdtime;

            return $this;
        }

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

        /**
         * Set modifiedtime
         *
         * @param \DateTime $modifiedtime
         * @return Products
         */
        public function setModifiedtime($modifiedtime) {
            $this->modifiedtime = $modifiedtime;

            return $this;
        }

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

        /**
         * Set deletedtime
         *
         * @param \DateTime $deletedtime
         * @return Products
         */
        public function setDeletedtime($deletedtime) {
            $this->deletedtime = $deletedtime;

            return $this;
        }

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

        /**
         * Set isdeleted
         *
         * @param boolean $isdeleted
         * @return Products
         */
        public function setIsdeleted($isdeleted) {
            $this->isdeleted = $isdeleted;

            return $this;
        }

        /**
         * Get isdeleted
         *
         * @return boolean 
         */
        public function getIsdeleted() {
            return $this->isdeleted;
        }

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

        /**
         * Set category
         *
         * @param \AppBundle\Entity\Categories $category
         * @return Products
         */
        public function setCategory(\AppBundle\Entity\Categories $category = null) {
            $this->category = $category;

            return $this;
        }

        /**
         * Get category
         *
         * @return \AppBundle\Entity\Categories 
         */
        public function getCategory() {
            return $this->category;
        }

        /**
         * Set type
         *
         * @param \AppBundle\Entity\ProductTypes $type
         * @return Products
         */
        public function setType(\AppBundle\Entity\ProductTypes $type = null) {
            $this->type = $type;

            return $this;
        }

        /**
         * Get type
         *
         * @return \AppBundle\Entity\ProductTypes 
         */
        public function getType() {
            return $this->type;
        }

        /**
         * Set currency
         *
         * @param \AppBundle\Entity\Currencies $currency
         * @return Products
         */
        public function setCurrency(\AppBundle\Entity\Currencies $currency = null) {
            $this->currency = $currency;

            return $this;
        }

        /**
         * Get currency
         *
         * @return \AppBundle\Entity\Currencies 
         */
        public function getCurrency() {
            return $this->currency;
        }

        /**
         * Add set
         *
         * @param \AppBundle\Entity\Sets $set
         * @return Products
         */
        public function addSet(\AppBundle\Entity\Sets $set) {
            $this->set[] = $set;

            return $this;
        }

        /**
         * Remove set
         *
         * @param \AppBundle\Entity\Sets $set
         */
        public function removeSet(\AppBundle\Entity\Sets $set) {
            $this->set->removeElement($set);
        }

        /**
         * Get set
         *
         * @return \Doctrine\Common\Collections\Collection 
         */
        public function getSet() {
            return $this->set;
        }

        /**
         * Add product
         *
         * @param \AppBundle\Entity\Products $product
         * @return Products
         */
        public function addProduct(\AppBundle\Entity\Products $product) {
            $this->product[] = $product;

            return $this;
        }

        /**
         * Remove product
         *
         * @param \AppBundle\Entity\Products $product
         */
        public function removeProduct(\AppBundle\Entity\Products $product) {
            $this->product->removeElement($product);
        }

        /**
         * Get product
         *
         * @return \Doctrine\Common\Collections\Collection 
         */
        public function getProduct() {
            return $this->product;
        }

        /**
         * Add document
         *
         * @param \AppBundle\Entity\Documents $document
         * @return Products
         */
        public function addDocument(\AppBundle\Entity\Documents $document) {
            $this->document[] = $document;

            return $this;
        }

        /**
         * Remove document
         *
         * @param \AppBundle\Entity\Documents $document
         */
        public function removeDocument(\AppBundle\Entity\Documents $document) {
            $this->document->removeElement($document);
        }

        /**
         * Get document
         *
         * @return \Doctrine\Common\Collections\Collection 
         */
        public function getDocument() {
            return $this->document;
        }

        /**
         * Add image
         *
         * @param \AppBundle\Entity\Images $image
         * @return Products
         */
        public function addImage(\AppBundle\Entity\Images $image) {
            $this->image[] = $image;

            return $this;
        }

        /**
         * Remove image
         *
         * @param \AppBundle\Entity\Images $image
         */
        public function removeImage(\AppBundle\Entity\Images $image) {
            $this->image->removeElement($image);
        }

        /**
         * Get image
         *
         * @return \Doctrine\Common\Collections\Collection 
         */
        public function getImage() {
            return $this->image;
        }

        // CUSTOM CODE
        /**
         * Set providerRate
         *
         * @param \AppBundle\Entity\ProviderRate $providerRate
         * @return Products
         */
     /*   public function setProviderRate(\AppBundle\Entity\ProviderRate $providerRate = null)
        {
            $this->providerRate = $providerRate;

            return $this;
        }
    */
         /**
         * Add providerRate
         *
         * @param \AppBundle\Entity\ProviderRate $providerRate
         * @return Products
         */
        public function addProviderRate(\AppBundle\Entity\ProviderRate $providerRate) {
            $this->providerRate[] = $providerRate;

            return $this;
        }

        /**
         * Remove providerRate
         *
         * @param \AppBundle\Entity\ProviderRate $providerRate
         */
        public function removeProviderRate(\AppBundle\Entity\ProviderRate $providerRate) {
            $this->providerRate->removeElement($providerRate);
        }

        /**
         * Get providerRate
         *
         * @return \AppBundle\Entity\ProviderRate 
         */
        public function getProviderRate()
        {
            return $this->providerRate;
        }
    }

ProviderRate Entity

  /**
     * ProviderRate
     *
     * @ORM\Table(name="provider_rate", indexes={@ORM\Index(name="fk_proveedor_has_producto_compra_producto_compra1_idx", columns={"product_id"}), @ORM\Index(name="fk_id_tarifa_proveedor_id_moneda1_idx", columns={"currency_id"}), @ORM\Index(name="IDX_3A645C45A53A8AA", columns={"provider_id"})})
     * @ORM\Entity(repositoryClass="AppBundle\Repository\ProviderRateRepository")
     */
    class ProviderRate
    {
        /**
         * @var string
         *
         * @ORM\Column(name="reference", type="string", length=45, nullable=false)
         */
        private $reference;

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

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

        /**
         * @var integer
         *
         * @ORM\Column(name="amount_per_unit", type="integer", nullable=true)
         */
        private $amountPerUnit;

        /**
         * @var string
         *
         * @ORM\Column(name="unit_price", type="decimal", precision=25, scale=3, nullable=false)
         */
        private $unitPrice;

        /**
         * @var string
         *
         * @ORM\Column(name="discount", type="decimal", precision=25, scale=3, nullable=false)
         */
        private $discount;

        /**
         * @var \AppBundle\Entity\Providers
         *
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="NONE")
         * @ORM\OneToOne(targetEntity="AppBundle\Entity\Providers")
         * @ORM\JoinColumns({
         *   @ORM\JoinColumn(name="provider_id", referencedColumnName="id")
         * })
         */
        private $provider;

        /**
         * @var \AppBundle\Entity\Products
         *
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="NONE")
         * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Products", inversedBy="providerRate")
         * @ORM\JoinColumn(name="product_id", referencedColumnName="id")
         * 
         */
        private $product;


        /**
         * Set provider
         *
         * @param \AppBundle\Entity\Providers $provider
         * @return ProviderRate
         */
        public function setProvider(\AppBundle\Entity\Providers $provider)
        {
            $this->provider = $provider;

            return $this;
        }

        /**
         * Get provider
         *
         * @return \AppBundle\Entity\Providers 
         */
        public function getProvider()
        {
            return $this->provider;
        }

        /**
         * Set product
         *
         * @param \AppBundle\Entity\Products $product
         * @return ProviderRate
         */
        public function setProduct(\AppBundle\Entity\Products $product)
        {
            $this->product = $product;

            return $this;
        }

        /**
         * Get product
         *
         * @return \AppBundle\Entity\Products 
         */
        public function getProduct()
        {
            return $this->product;
        }

    }

The code to run on the controller is as follows:

public function ajaxNewProductAction() {
        $request = $this->getRequest();

        $product    = new Products();
        $form       = $this->createForm(new ProductsType(), $product);
        $form->handleRequest($request);
        if ($request->getMethod() == 'POST') {
            if ($form->isSubmitted() && $form->isValid()) { // Se procesa el formulario
                $em             = $this->getDoctrine()->getManager();
                $providerId     = $request->get('provider');
                $productVals    = $request->get('Products');
                $currency       = $em->getRepository('AppBundle:Currencies')->findOneByName("Euro");

                $product->setCurrency($currency);
                $product->setType($em->getRepository('AppBundle:ProductTypes')->findOneById(1));
                $product->setIsactive(1);

                $em->persist($product);
                $em->flush();


                $response['success'] = true;
                $response['data'] = 0;
                $response['providerId'] = $providerId;
            }
            else {
                $response['success'] = false;
                $response['cause'] = 'whatever';
            }
            return new JsonResponse($response);
        }

        return $this->render(':products/ajax:newProduct.html.twig', array("form" => $form->createView(), "edit" => false));
    }

Answer:

SOLVE:

I can solve it. The code of my entities thats ok. I change the controller function. First I create the product object, set the providerRate to null and them persist it. After I create the providerRate object and set the product object.

public function ajaxNewProductAction() {
        $request = $this->getRequest();

        $product    = new Products();
        $form       = $this->createForm(new ProductsType(), $product);
        $form->handleRequest($request);
        if ($request->getMethod() == 'POST') {
            if ($form->isSubmitted() && $form->isValid()) { // Se procesa el formulario
                $em             = $this->getDoctrine()->getManager();
                $providerId     = $request->get('provider');
                $productVal     = $request->get('Products');
                $currency       = $em->getRepository('AppBundle:Currencies')->findOneByName("Euro");

                $product->setCurrency($currency);
                $product->setType($em->getRepository('AppBundle:ProductTypes')->findOneById(1));
                $product->setProviderRate(null);
                $em->persist($product);
                $em->flush();

                $providerRate = new ProviderRate();
                $providerRate->setProvider($em->getRepository('AppBundle:Providers')->findOneById($providerId));
                $providerRate->setProduct($product);
                $providerRate->setReference($productVal["providerRate"][1]["reference"]);
                $providerRate->setName($productVal["name"]);
                $providerRate->setDescription($productVal["description"]);
                $providerRate->setAmountPerUnit(1);
                $providerRate->setUnitPrice(0);
                $providerRate->setDiscount(0);
                $providerRate->setCurrency($currency);

                $providerRate->setProduct($product);
                $em->persist($providerRate);
                $em->flush();

                $response['success'] = true;
            }
            else {
                $response['success'] = false;
                $response['cause'] = 'Algo ocurrió';
            }
            return new JsonResponse($response);
        }

        return $this->render(':products/ajax:newProduct.html.twig', array("form" => $form->createView(), "edit" => false));
    }

Related:


wkhtmltopdf on openSuSE: cannot connect to X server


php,symfony2,pdf-generation,twig,wkhtmltopdf
I need wkhtmltopdf on openSuSE. I have installed it via the repository. The version is 0.12.1. To render HTML with Symfony, I use the KnpSnappyBundle. By rendering a twig template, I got the following error message: The exit status code '1' says something went wrong: stderr: "wkhtmltopdf: cannot connect to...

Force Uppercase on Symfony2 form text field


php,forms,symfony2
I've inherited a Symfony2 project that has a form built as such: $builder ->add('Status', 'choice', array( 'choices' => array('' => '', 'PASS' => 'PASS', 'FAIL' => 'FAIL', 'INCOMPLETE' => 'INCOMPLETE', 'DROPPED' => 'DROPPED',), 'required' => FALSE, )) ->add('First_Name', 'text', array('label'=>'First Name', 'required' => FALSE)) ->add('Last_Name', 'text', array('label'=>'Last Name', 'required' =>...

Symfony/Twig radio style formbuilder


php,symfony2,twig,formbuilder
I need to style each of radio button using Symfony form builder. This is my part of my createFormBuilder: ->add('categoryId', 'entity', array( 'class' => 'MyBundle:Category', 'property' => 'name', 'required' => false, 'expanded' => true )) And in my twig template: {% for child in form.categoryId %} <div class="radio i-checks col-md-3">...

Symfony\Component\Config\Exception\FileLoaderLoadException] error


php,symfony2,twig,swiftmailer
Hi I stumble upon this error everytime I want to run my Symfony application from console. Therefore I am unable to use this symphony app at all. Please help me with your knowledge. [Symfony\Component\Config\Exception\FileLoaderLoadException] Unable to parse at line 9 (near "mailer_transport="gmail"") in /opt/lampp/htdocs/symblog.dev/app/config/parameters.yml (which is being imported from "/opt/lampp/htdocs/symblog.dev/app/config/config.yml")....

Setting cookie for AngularJS translate locale using PHP


php,angularjs,symfony2,angular-translate
My app uses Symfony and AngularJS. I have translations some with Symfony itself and some with AngularJS angular-translate. How do I set a cookie or session variable to change language for AngularJS from PHP?

Logs an entire array using Monolog [closed]


php,symfony2,monolog,symfony-2.6
Is there any way to log an entire array using Monolog? I have been reading several docs but didn't find a way to log the entire array in a readable format, any advice? Docs I've read: Monolog, how to log PHP array into console? http://symfony.com/doc/current/cookbook/logging/monolog.html https://www.webfactory.de/blog/logging-with-monolog-in-symfony2 ...

Symfony change validation message globally


php,symfony2,symfony-2.3
Is there a way to change the basic validation error message to one I need for all entities at once? Currently using Yaml config for every entity, but it's not a way. CF\MyBundle\Entity\User: properties: email: - Email: message: e-mail no válido - NotBlank: message: Campo obligatorio username: -NotBlank: message: Campo...

Set Auth Token manually for different firewall


symfony2
My application has 2 security firewalls "admin" - used by internal staff "account" - used by customers. Previoly I had one action under the account firewall, the action in the controller looks something like this. $user = //get user somehow $token = new UsernamePasswordToken($user, null, 'account', $user->getRoles()); $this->get('security.token_storage')->setToken($token); With this...

comparison operator is not working in twig


php,symfony2
problem in comparing dates in twig. case if event is ongoing or is about to begin within 7 days. twig code {% set event_startdate=data.detailes.data.event.event_startdate|date("d-m-Y")%} {% set event_enddate=data.detailes.data.event.event_enddate|date("d-m-Y") %} {% set upcoming_days =daysdiff(event_startdate)|date('d-m-y') %} {% set stdate= "now"|date('d-m-y') %} {% if event_startdate >stdate and event_startdate < upcoming_days %} // condition...

AngularJS execute some action in all application instances


angularjs,symfony2
I have AngularJS app called myApp. It has several controllers which are used in different pages (website is based on Symfony so page reloads happens sometimes). I need to execute some lines of code in every controller. how do I do that without duplicating that code?

Store entity from session doesn't work => $em->persist()


php,symfony2,doctrine2
at first: Sorry for my poor english :-) A beginner need help! I have 3 entities/tables: Tables: contact_person id, title, firstname, surname, adress_id address id, street, zip, city, country_id country (fix values) id, name, code 1, Austria, AT 2, Germany, DE ... Entities: /** * ContactPerson * * @ORM\Table(name="contact_person") *...

WebTestCase, Silex and $_GET


symfony2,silex,web-testing
I'm experiencing some issues on a WebTestCase using Silex: on one of my controller's action, I need a parameter passed through a normal $_GET (I have to as it's an URL, and Apaches interprets the %2F if it's outside of the query string -- see Url Variables with %2f not...

With a OneToMany relation between entities, how create the right queryBuilder with Doctrine (on the Inversed Side entity)


php,symfony2,doctrine2,one-to-many,query-builder
I have these 3 entities in my symfony2.6 project: Compteurs.php class Compteurs { /** * @var \PointsComptage * * @ORM\ManyToOne(targetEntity="PointsComptage", inversedBy="compteurs") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="pointscomptage_id", referencedColumnName="id") * }) */ private $pointsComptage; /** * @var \Doctrine\Common\Collections\Collection * * @ORM\OneToMany(targetEntity="ParametresMesure", mappedBy="compteurs") */ private $parametresMesure; ParametresMesure.php: class ParametresMesure { /** * @var Compteurs...

ClassNotFoundException Symfony UserBundle


symfony2,fosuserbundle
I'm developping a website on Symfony2, I want to intergrate FOSUserBundle. I am using Doctrine ORM User class. I've followed the installation steps but I got this error: ClassNotFoundException in AppKernel.php line 21: Attempted to load class "FOSUserBundle" from namespace "FOS\UserBundle". Did you forget a "use" statement for another namespace?...

Deserializing or parse XML response in Symfony2


php,xml,symfony2,deserialization,jmsserializerbundle
I am calling a API method through cURL and I got this response: <?xml version="1.0" encoding="UTF-8"?> <jobInfo xmlns="http://www.force.com/2009/06/asyncapi/dataload"> <id>75080000002s5siAAA</id> <operation>query</operation> <object>User</object> <createdById>00580000008ReolAAC</createdById> <createdDate>2015-06-23T13:03:01.000Z</createdDate> <systemModstamp>2015-06-23T13:03:01.000Z</systemModstamp> <state>Open</state>...

Symfony2 creating and persisting entity relationships


php,mysql,symfony2,doctrine2
I have two entities Skin and Email. I want Email to be a part of the Skin entity, however I can't use the console to update schema automatically right now, and that is probably why I can't get the relationship to work. So I want to store all the Emails...

How adapt the path to the previous and next article


php,symfony2
I am looking for a solution to access in the current article to the previous(<<) or the next article(>>) at the end of the page of an article. I thought to get the current paramater of the url with this : {{ dump(app.request.attributes.get('_route_params')) }} and inject in the path with...

Symfony Entity query builder that checks for free spots


php,mysql,symfony2,doctrine2,dql
First off all: I know the title isn't helping, but it's the best I can think of. So I've got two entities in Symfony one is called Team and the other one Slot the Slot entity has a name, a start and end date and all that stuff. Besides that...

Using crontab to call wget every 5 minutes


php,symfony2,crontab,wget
I am working on a project where the wget and crontab are used to run a process in the background. I have a php file named "Hello.php" that I want to run this every 5 minutes. I have found that if I want to have a cron job run every...

Symfony2/Twig - iterate over select options


php,symfony2,twig
Usual way of displaying select field is to call {{ form_row(form.doctor_service_id, {'attr':{'class':'form-control'}}) }} I would like to perform two things: Check if this field is actually a select field Iterate over every option (value, name). I know how twig iterator works, I just don't know how to access select options...

Update session in symfony2 for shoppingg cart


php,symfony2,symfony-2.1,php-5.3,symfony-2.3
I have the following code : public function addAction(Request $request){ //Get submited data // Get Value from session $sessionVal = $this->get('session')->get('aBasket'); // Append value to retrieved array. $aBasket = $request->request->all(); if(count($sessionVal) > 0) { foreach ($sessionVal as $key=>$value) { if($aBasket['product_id'] == $sessionVal[$key]['product_id']) { $sessionVal[$key]['product_quantity'] = $sessionVal[$key]['product_quantity'] + $aBasket['product_quantity'];...

Symfony 2 unable to pass entity repository to form


php,forms,symfony2,runtime-error
I have a form with a drop down and a set of checkboxes, i've used entity form field type to get the values via DB. it works with one of the entity but not with the other. i have this code seperately inside AddBadgesType there is NO AddBadges entity <?php...

Validation of a form before submission


php,validation,symfony2,form-submit
Using Symfony, version 2.3 and more recent, I want the user to click on a link to go to the edition page of an already existing entity and that the form which is displayed to be already validated, with each error associated to its corresponding field, i.e. I want the...

Symfony/Twig how to render a Route set by anotation?


php,symfony2,routing,twig,url-routing
Let's say I have this code in a controller: <?php namespace Foo\BarBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration as Mvc; /** * @Mvc\Route("/foo/bar") */ class TestController extends Controller /** * @Mvc\Route("/test/{id}", requirements={"id" = "[0-9]{1,6}"}) * @Mvc\Template * * @return view */ public function testAction($id) { return array('test' => $id); } } How...

Symfony 2 - Class “Mingle\StandardBundle\Entity\Product” is not a valid entity or mapped superclass


php,symfony2,doctrine,entity,bundle
I created a Product.php file in my bundle Mingle\StandardBundle\Entity like this: <?php namespace Mingle\StandardBundle\Entity; use Doctrine\ORM\Mapping as ORM; /* * @ORM\Entity * @ORM\Table(name="product") */ class Product { /* * @ORM\Column(type="integer") * @ORM\ID * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /* * @ORM\Column(type="string",length=100) */ protected $name; /* * @ORM\Column(type="decimal",scale=2) */ protected $price; /*...

Setup VPS with a Symfony2 project from git repository


symfony2,vps
I have a: - VPS with LAMP stack - local symfony2 project (git) - bitbucket repository What do I need to do to properly setup my project in the production evironment? Folder structure/permissions? Can I simply clone the repository in the public folder? (I don't think so) P.s. I've already...

Class inheritance in Symfony2


php,symfony2,doctrine2
I'm a bit confused about an error that I'm getting: Undefined method 'getAsArray'. The method name must start with either findBy or findOneBy! getAsArray() is a method in my repository class, it's called in PostsController.php like so: $categoriesList = $this->getDoctrine()->getRepository('AirBlogBundle:Category')->getAsArray(); CategoryRepository.php is defined like this: namespace Air\BlogBundle\Repository; class CategoryRepository extends...

Unable to configure Symfony (3rd party) bundle


php,symfony2,rss
I am faily new to Symfony and I am trying to setup a third party bundle that reads RSS feeds and then insert them into database. The third party bundle I am trying to use is called rss-atom-bundle After reading the instructions I can get the RSS feeds however I...

How to select all rows that don't have one-to-many entity with certain value using Doctrine


php,mysql,orm,doctrine2,doctrine
I have two entities: Cage and Bird. Cage has Birds inside so their relationship is one-to-many. Bird has a field name. How can I select all Cages where there's no Bird with name eagle inside. I was trying to do this: $cages = $this->createQueryBuilder("c") ->leftJoin("c.birds", "b") ->where("b.name != :name") ->setParameter("name",...

Symfony2: changing the request class and updating the test environment


php,symfony2,request,phpunit
I have modified the base Request class of my application as explained in the accepted answer of this question. It works very well, except when launching my functional tests, I get the following error: Controller "My\Bundle\AppBundle\Controller\MyController::searchAction()" requires that you provide a value for the "$request" argument (because there is no...

Symfony files which are included in CSS are not found when using assetic


css,symfony2,twig,assetic
I'm using Symfony with Twig and I use assetic. The problem is that my CSS file includes other CSS files like that: @import url(ie8.css); @import url(blocks.css); @import url(plugins.css); @import url(app.css); And these files are not found when webpage is displayed. Same happens with fonts and images. How do I solve...

Symfony one-to-one, unidirectional relation


symfony2,doctrine2
I have two entities. User and Contact. User and contact have the same property phone_number. I would like to get all contacts with user object if its exists. It is also possible that the same phone number exists in contact table but it doesn't exist in user table. Below is...

Symfony2 Catchable Fatal Error: Argument 1 passed to entity Catchable Fatal Error: Argument 1 passed to entity


php,forms,symfony2,entity,symfony-2.6
I got this error and I'm stuck since many hours Catchable Fatal Error: Argument 1 passed to Thinking\ThinkBundle\Entity\InYourMind::setThinkFriend() must be an instance of Thinking\ThinkBundle\Entity\InYourMindFriend, array given, called in /var/www/html/thinkroulette/vars/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php on line 410 and defined I searched for this issue and lots of results came up but I wasn't capable to...

order attribute of an object in Synfony


php,symfony2
I would like to reorder the attribute (COMMENTS) of my object (instance of ARTICLE) after I retrieve it from the DBB. Is this possible? My object is ARTICLE and it is linked to COMMENTS (which is defined as a collection in entity article) I know I can order through the...

doctrine does not hydration when select custom fields


doctrine2,doctrine,doctrine-query
i have tried select fields with doctrine query buidler. $queryBuilder = $entityManager->createQueryBuilder(); $queryBuilder->select('au.id, au.firstName') ->from('Api\V1\Entity\AgencyUser', 'au') ->orderBy('au.firstName', 'asc'); $queryBuilder->andWhere('au.agency = :agencyId') ->setParameter('agencyId', $agency->getId()); print_r($queryBuilder->getQuery()->getResult(Query::HYDRATE_OBJECT));exit; result : Array ( [0] => Array ( [id] => 1 [firstName] => agency ) ) why this is an array ? i want to hydrated...

Remove automaticaly entity in BD when choice value not selected (or null selected)


php,forms,symfony2,doctrine
I would like to know if symfony/doctrine can manage automaticaly the fact that instead of setting the value of my entity to null it could symply remove it. (by removing it I mean the records where the value equal null) exemple: I have a PICTURE entity linked to a VOTE...

Symfony2 service unable to find template


php,email,symfony2,templates,twig
I've just pulled an all-nighter trying to get this to work, and I'm probably missing something foolish, but help me out. I have a symfony2 service which sends emails. I have injected the @templating service into my service's constructor like so: services.yml order_service: class: AppBundle\Services\OrderService arguments: [ "@doctrine.orm.entity_manager", "@mailer", "@templating"...

How to write and use Monolog handlers and channels


php,symfony2,monolog,symfony-2.6
I have read some docs here but still not clear to me how to write and use a custom Monolog handler and channel. Let me explain a bit what I want to achieve. I have a custom function and I want that log to be logged into a file called...

Symfony2: ajax call redirection if session timedout


ajax,symfony2,session
I have a working dashboard with ajax request. I fire an ajax request on some events which will update a part of the dashboard. But if the session has expired, the part will be refreshed with the login page. How can i do a redirection after the ajax call if...

Symfony2 move app.php from web directory to root directory


symfony2
I moved app.php from web directory to root and i change the following two lines: $loader = require_once __DIR__.'/app/bootstrap.php.cache'; require_once __DIR__.'/app/AppKernel.php'; Also i move .htaccess file from web directory to root , my problem is that now the system cannot find JavaScript and CSS files....

Unique Entity Error message


api,symfony2,exception-handling,doctrine
I have a user entity which have some unique fields. The code bellow shows you how I defined it. /** * @UniqueEntity(fields={"login"}, message="UNIQUE ERROR MESSAGE") */ ...... /** * @var string * * @ORM\Column(name="login", type="string", length=255, unique=true) */ private $login; Developping an API, I would like to be able to...

How to create a console command in Symfony2 application


php,symfony2,symfony-2.6,symfony-components,symfony-console
I need to create a console command for a Symfony2 application and I read docs here and here though I am not sure what of those I should follow. So this is what I did. Create a file under /src/PDI/PDOneBundle/Console/PDOneSyncCommand.php Write this code: namespace PDI\PDOneBundle\Console\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use...

Symfony Crawler: how to check that a link to a particular page exists


php,symfony2,phpunit,functional-testing
I'm writing some functional tests and i want to verify that the Edit link exists on the page if the user is logged in. The link is a simple <a href="/profile/22/edit">Edit</a>. How can I filter it using the Crawler component of Symfony? One solution is this: $this->assertEquals(1, $crawler->filter('html:contains("<a href="/profile/22/edit">")')->count()); But...

symfony twig render dynamic twig code


symfony2,twig
In my symfony2 action, i have: $twigCode = '<li>{{ data.value }}</li>'; //In database $datas = array(array( 'value' => 'line 1'), array( 'value' => 'line 2')); return $this->render( '...List.html.twig', array( 'twigCode' => $twigCode, 'datas' => $datas ) ); In my twig template, i want something like: <ul> {% for data in...