kim.kaho February 2016

Symfony3 - Combine forms

I have 2 ORM entities (Customer and Address) which I want to combine into one form. When a new Customer is created also an new Address must be created (with type is set to 'invoice' by default)

My current code is like this.

Entities

|Customers| -1----N-> |Address|

class Customer
{
...

/**
 * @ORM\OneToMany(targetEntity="Address", mappedBy="customer")
 */
protected $addresses;
...
}

class Address
{
...
/**
 * @var string
 *
 * @ORM\Column(name="type", type="string", length=255)
 */
private $type; // (Invoice / Delivery)

/**
 * @ORM\ManyToOne(targetEntity="Customer", inversedBy="addresses")
 * @ORM\JoinColumn(name="customer_id", referencedColumnName="id")
 */
protected $customer;
...
}

The Controllers actions

/**
 * Creates a new Customer entity.
 *
 * @Route("/new", name="customer_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request)
{
    $customer = new Customer();
    $form = $this->createForm('Rekursief\CrmBundle\Form\CustomerType', $customer);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($customer);
        $em->flush();

        return $this->redirectToRoute('customer_show', array('id' => $customer->getId()));
    }

    return $this->render('customer/new.html.twig', array(
        'customer' => $customer,
        'form' => $form->createView(),
    ));
}
/**
 * Creates a new Address entity.
 *
 * @Route("/new", name="address_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request)
{
    $address = new Address();
    $form = $this->createForm('Rekursief\CrmBundle\Form\AddressType', $address);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctri        

Answers


Cerad February 2016

Assume that we have a business rule which states that every customer has at least one address. We can implement this rule by creating an address in the customer's constructor.

class Customer
{
  public function __construct()
  {
    $this->addresses = new ArrayCollection();
    $address = new Address();
    $this->addAddress($address);
  }
  public function addAddress(Address $address)
  {
    $this->addresses[] = $address;
    $address->setCustomer($customer);
  }

Post Status

Asked in February 2016
Viewed 2,707 times
Voted 14
Answered 1 times

Search




Leave an answer