Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9120829
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T05:42:43+00:00 2026-06-17T05:42:43+00:00

I’m new to Symfony2 . I have problem about One-To-Many relationship. My code is,

  • 0

I’m new to Symfony2. I have problem about One-To-Many relationship.

My code is,

Here, Product-Size, product_id return null.

Product Entity :

namespace Front\ProductBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

class Product
{
  //
  /**
  * @ORM\OneToMany(targetEntity="Size", mappedBy="product", cascade={"persist"})
  */
  public $size;

  public function __construct()
  {
    $this->size = new ArrayCollection();
  }
  /**
   * Add size
   *
   * @param Front\ProductBundle\Entity\Size $size
   */
  public function addSize(\Front\ProductBundle\Entity\Size $size)
  {
      $this->size[] = $size;
  }

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

Size Entity:

namespace Front\ProductBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
class Size
{
//
  /**
   * @ORM\ManyToOne(targetEntity="Product", inversedBy="size", cascade={"persist"})
   * @ORM\JoinColumn(name="product_id", referencedColumnName="id")
   */
  protected $product;

  /**
  * Set product
  *
  * @param Front\ProductBundle\Entity\Product $product
  */
  public function setProduct(\Front\ProductBundle\Entity\Product $product)
  {
    $this->product = $product;
  }

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

My Controller:

namespace Admin\ProductBundle\Controller;


use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

// Entity
use Front\ProductBundle\Entity\Product;
use Front\ProductBundle\Entity\Size;

use Admin\ProductBundle\Form\Type\ProductType;
use Admin\ProductBundle\Form\Type\SizeType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;


class AdminController extends Controller
{
public function createAction(Request $request)
    {
      $category = new Category();
      $product = new Product();

      //make 3 size for product
      $size1 = new Size();
      $product->addSize($size1);

      $size2 = new Size();
      $product->addSize($size2);

      $size3 = new Size();
      $product->addSize($size3);

      $form = $this->createForm(new ProductType(), $product);

      //write data
      if($request->getMethod() == 'POST'){
          $form->bindRequest($request);

          //check validate
          if ($form->isValid()){
            //persist data() to database
            $em = $this->getDoctrine()->getEntityManager();
            $product->upload();
            $em->persist($product);
            $em->flush();

            //set Message Flash and redirect
            $this->get('session')->setFlash('notice_success', 'Success Message ');

            return $this->redirect($this->generateUrl('_admin_home'));
          }
        }


        return $this->render('AdminProductBundle:Admin:create.html.twig', array(
            'form' => $form->createView(),
        ));
    }

My View:

...
<div>
{% for size in form.size %}
  <div id="sizeField">
    <div class="blockSizeForm">
     {{ form_label(size.name) }}
     {{ form_widget(size.name) }}
   </div>
   <div class="blockSizeForm">
     {{ form_label(size.price) }}
     {{ form_widget(size.price) }}
       </div>
     </div>
    {% endfor %}
</div>

Product Form and Size Form:

Product Form:

namespace Admin\ProductBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ProductType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('size', 'collection', array(
                'type' => new SizeType(),
                'allow_add' => true,
                'by_reference' => false,
            ));
    }
    public function getDefaultOptions(array $options)
    {
        return array(
        'data_class' => 'Front\ProductBundle\Entity\Product',
        'error_bubbling'=>true,
        );
    }

    public function getName()
    {
        return 'Product';
    }
}

Size Form:

namespace Admin\ProductBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class SizeType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('name','text',array(
                'label' => 'name:',
                ))
            ->add('price','money',array(
                'label' => 'value:',
                ));
    }
    public function getDefaultOptions(array $options)
    {
        return array(
        'data_class' => 'Front\ProductBundle\Entity\Size',
        'error_bubbling'=>true,
        );
    }

    public function getName()
    {
        return 'Size';
    }
}

PROBLEM:
I can create new success. But product_id for Size table return Null.

help me.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T05:42:45+00:00Added an answer on June 17, 2026 at 5:42 am

    When you save entities in doctrine, the owning side must persist the relationship: http://docs.doctrine-project.org/en/latest/reference/unitofwork-associations.html

    In your code, the owning side is the Size entity as the entity with the ManyToOne description above the parameter is always the owning side. This means you need to persist the Size entities not the product entities.

    I think something like:

          if ($form->isValid()){
            //persist data to database            
            $em = $this->getDoctrine()->getEntityManager();
            $product->upload();
            // loop through as set the relationship for each size
            foreach($product->getSize() as $size){
              $size->setProduct($product);
            }
            $em->persist($product);
            $em->flush();
    
            //set Message Flash
            $this->get('session')->setFlash('notice_success', 'Success Message ');
    
            return $this->redirect($this->generateUrl('_admin_home'));
          }
    

    Your cascade persist should take care of the rest

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this code to decode numeric html entities to the UTF8 equivalent character.
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I don't have much knowledge about the IPv6 protocol, so sorry if the question
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have been unable to fix a problem with Java Unicode and encoding. The
I have a reasonable size flat file database of text documents mostly saved in
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.