Reputation: 2810
I have a User entity that has an ArrayCollection of Subscriptions. I have these setters and getters.
public function addSubscription(\Doge\WowBundle\Entity\Subscription $subscription)
{
$this->subscriptions[] = $subscription;
return $this;
}
public function removeSubscription(\Doge\WowBundle\Entity\Subscription $subscription)
{
$this->subscriptions->removeElement($subscription);
}
public function getSubscriptions()
{
return $this->subscriptions;
}
There is another entity called Plan. A Subscription is basically the intermediate entity between User and Plan, except it holds an extra field so it is necessary to be a dedicated entity.
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="subscriptions")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $user;
/**
* @ORM\ManyToOne(targetEntity="Plan", inversedBy="subscriptions")
* @ORM\JoinColumn(name="plan_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $plan;
/**
* @ORM\Column(type="date")
*/
protected $nextDue;
Otherwise, it would just be a many-to-many relationship with an automatic intermediate table generated.
Now in the User registration form, a user can choose between plans available in the Plans table with this code in the FormBuilder
$builder->add('subscriptions', 'entity', array('class' => 'DogeWowBundle:Plan'))
How can I create a new Subscription object given the Plan object? Would I do so in the controller? Use a datatransformer? What is the best practice for this?
Upvotes: 2
Views: 88
Reputation: 2769
you have 2 options, the first is that you have a form that contains a form. One form is mapped to your user and the second is mapped to your subscription. So basically in your user form you would have
$builder->add('subscriptions', new SubscriptionsType())
and within that SubscriptionsType you would have your entity for plans like:
$builder->add('plan', 'entity', array(
'class' => 'DogeWowBundle:Plan',
'property' => 'plan_name',
));
this way your subscriptions will be auto generated and updated as necessary.
You could also use a data transformer, but i personally like using forms within forms.
Upvotes: 1