Symfony2 - Managing Entity Relations To Unused Entities When Persisting

129 Views Asked by At

I have two entities (Customer & PhoneNumber) which are in realtion with each other via a ManyToMany connection.

When trying to display both entities in one form, I use the following statements:

$customer = new Customer();
$customer->addPhoneNumber(new PhoneNumber());
$form = $this->createForm(new CustomerType(), $customer, array(
    'action' => $this->generateUrl('customer_add'),
));

After validation of the form I need to check whether or not the PhoneNumber section in the form has been used or not as entering a phone number is not a requirement. The reason I need to do so is: When trying to persist a customer that has a PhoneNumber-Entity connected to it which has no values set (= NULL values), I get a NOT NULL-Error from the database.

So what I do is: After validating the form, I remove the PhoneNumber-Entity-Relation to the customer in case no phone number has been entered.

$phoneNumber = $customer->getPhoneNumbers()->first();
if(empty($phoneNumber->getPrefix()) && empty($phoneNumber->getNumber())) {
    $customer->removePhoneNumber($phoneNumber);
}

That causes the following problems:

  • I no longer have a relation to a phone number entity. Now I have to do various check-ups on the relationships of the customer-entity each time I'm using it.
  • Also I don't like the fact that I'm editing the customer entity after validating it successfully.
  • In case an entity has a lot of relations to other entities, this adding and removing process I'm doing here can get very ugly and confusing.

Is there a better way to do what I am trying to do here?


Customer.php:

/**
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\PhoneNumber", mappedBy="customers", cascade={"persist"})
 * @Assert\Valid()
 **/
protected $phoneNumbers;

PhoneNumber.php:

/**
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Customer", inversedBy="phoneNumbers", cascade={"persist"})
 * @ORM\JoinTable(name="cp_relation")
 **/
protected $customers;

CustomerType.php:

# ...
->add('phoneNumbers', 'collection', array(
          'type' => new PhoneNumberType(),
          'options' => array(
              'required' => false,
          )
     ))
1

There are 1 best solutions below

0
ghanbari On BEST ANSWER

As discussed in chat room, the best solution is that use collection type and set allow_add=true and by use of jQuery & prototype field, let user to add fields.

But in your case(because you don't want use jquery and rely on js), you can render static field as (don't forget to set allow_add=true):

<input type="email" id="form_emails_0" name="form[emails][0]" value="" /><br>
<input type="email" id="form_emails_1" name="form[emails][1]" value="" />