easyadmin crud controllers: adding value into related entity - php

I have question concerning easyadmin3. In my admin panel I have a productCrudController and one of the values I want to be able to set when creating a new product is the price.
For the price I have a separate table though which contains all my prices with a date. The idea being that the price of a product van change over time and my client wants to be able to have an overview of the price history for each product.
So in my productCrudController I work with an associationField to link to my prices entity. However I'm really stuck with the following practical issue: I don't want to have to add a price in a priceCrudController which I would then be able to select in my productCrudController (the way the associationField expects me to do).
What I want is that I can create a product and input a price which would then be inserted into my prices table.
My code:
productCrudController ->
Right now I have a field for prices where I can select a price in a dropdown menu, but so I have to add the price first with a priceCrudController, which really isn't practical.
class ProductsCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return Products::class;
}
public function configureFields(string $pageName): iterable
{
$image = ImageField::new('image')->setBasePath('resources/images');
$imageFile = TextField::new('imageFile')->setFormType(VichImageType::class);
$fields = [
IdField::new('id', 'ID')->hideOnForm(),
TextField::new('name'),
TextEditorField::new('description'),
AssociationField::new('category'),
AssociationField::new('plants')->setTemplatePath('list.html.twig'),
NumberField::new('stock'),
AssociationField::new('prices', 'bruto price')->onlyOnIndex()->setTemplatePath('price.html.twig'),
];
if($pageName == Crud::PAGE_INDEX || $pageName == Crud::PAGE_DETAIL){
$fields[] = $image;
} else {
$fields[] = $imageFile;
}
return $fields;
}
I tried just making a numberField for 'prices' to see if I could just enter a value that would then be persisted in the database, but I get the following error:
Object of class Doctrine\ORM\PersistentCollection could not be
converted to string
This is my 'prices' property in my 'products' entity and the methods:
/**
* #ORM\OneToMany(targetEntity=Prices::class, mappedBy="product")
* #Groups({"products:read"})
*/
private $prices;
/**
* #return Collection|Prices[]
*/
public function getPrices(): Collection
{
return $this->prices;
}
public function addPrice(Prices $price): self
{
if (!$this->prices->contains($price)) {
$this->prices[] = $price;
$price->setProduct($this);
}
return $this;
}
public function removePrice(Prices $price): self
{
if ($this->prices->removeElement($price)) {
// set the owning side to null (unless already changed)
if ($price->getProduct() === $this) {
$price->setProduct(null);
}
}
return $this;
}
I have the feeling I might need to do something with event listeners, but I don't really know how to go about it as I haven't really worked with them before.
I'd be very grateful for any help

You can create a form for the Prices entity and then use it in your product
CollectionField::new('prices')
->hideOnIndex()
->setLabel('bruto price')
->setTemplatePath('price.html.twig')
->setFormTypeOptions([
'label' => false,
'delete_empty' => true,
'by_reference' => false,
])
->setEntryIsComplex(false)
->setCustomOptions([
'allowAdd' => true,
'allowDelete' => false,
'entryType' => PricesType::class, // Your price form class here
'showEntryLabel' => false,
])
;

Related

Laravel doctrine2 many to many relation with extra column

So I'm beginning to struggle with Doctrine2 when it comes to a many-to-many relation for a project where the relation has 1 extra column.
I have the following tables:
Profiles
id
extra data
Skills
id
name
profile_has_skills
profile_id
skill_id
level
Now I added the level column later on, and noticed some problems happening, of course I am missing level now whenever I try to create the relation.
My question is, with the code below, how would I go over to add this in my doctrine?
My controller:
public function store(Request $request)
{
$time = new DateTime();
$this->validate($request, [
'name' => 'required',
'lastname' => 'required',
'gender' => 'required',
'profile_skills' => 'required'
]);
$this->em->getConnection()->beginTransaction();
try {
$profile = new Profile(
$request->input('company_id'),
$request->input('name'),
$request->input('lastname'),
$request->input('gender'),
new DateTime(),
$time,
$time
);
$company = $this->em->getRepository(Company::class)->find($request->input('company_id'));
$profile->addCompany($company);
foreach($request->input('profile_skills') as $skill => $level) {
$skill = $this->em->getRepository(Skill::class)->find($skill);
$skill->level = $level;
$profile->addSkill($skill);
}
$this->em->persist($profile);
$this->em->flush();
$this->em->getConnection()->commit();
} catch (OptimisticLockException $e) {
$this->em->getConnection()->rollBack();
throw $e;
}
return redirect(route('profiles.index'));
}
My ProfileHasSkill entity looks as follow:
/**
* #ORM\Entity
* #ORM\Table(name="profile_has_skill")
*
*/
class ProfileHasSkill
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #Column(type="integer", name="profile_id")
*/
protected $profile_id;
/**
* #Column(type="integer", name="skill_id")
*/
protected $skill_id;
/**
* #Column(type="integer", name="level")
*/
protected $level;
/**
* #param $profile_id
* #param $skill_id
* #param $level
*/
public function __construct($profile_id, $skill_id, $level = 0)
{
$this->profile_id = $profile_id;
$this->skill_id = $skill_id;
$this->level = $level;
}
And my addSkill method inside the profile entity is as follow:
public function addSkill(Skill $skill)
{
if ($this->skills->contains($skill)) {
return;
}
return $this->skills->add($skill);
}
But anytime I try to run this it gives me the following error
An exception occurred while executing
'INSERT INTO profile_has_skill (profile_id, skill_id) VALUES (?, ?)'
with params [3, 2]: SQLSTATE[HY000]: General error: 1364 Field 'level'
doesn't have a default value
Now I know one way to get rid of this error is setting a default value in the database, but I much rather just find out why it's not picking up my skill level that I'm also passing?
As per my solution which has worked, by reading another question passed by #Nicola Havric - Read as follow That doctrine does not support extra columns in a many-to-many relation. Thus you should use the relation as it's own entity. My own solution was to change the way I wanted it to run with flushing.
In my controller I changed my code as follow:
try {
$profile = new Profile(
$request->input('company_id'),
$request->input('name'),
$request->input('lastname'),
$request->input('gender'),
new DateTime(),
$time,
$time
);
$company = $this->em->getRepository(Company::class)->find($request->input('company_id'));
$profile->addCompany($company);
//Flush the user, so I can grab it's profile ID
$this->em->persist($profile);
$this->em->flush();
foreach($request->input('profile_skills') as $skill => $level) {
$skill = $this->em->getRepository(Skill::class)->find($skill);
$skill->level = $level;
$profile->addSkill($skill);
}
$this->em->getConnection()->commit();
Inside my Profile Entity function:
public function addSkill(Skill $skill)
{
//I left this check since it only checks if the relation is set already. If so, it will skip it.
if ($this->skills->contains($skill)) {
return;
}
//Since this function gets called inside a loop, I can call the entity to add a new "relation" to the table.
(new ProfileHasSkill($this->getId(), $skill, $skill->level))->addSkill($this->getId(), $skill, $skill->level);
return true;
}
Inside my ProfileHasSkill entity:
public function addSkill($profileId, $skill)
{
//Creating a new ProfileHasSkill inside the table.
$profileSkill = new ProfileHasSkill(
$profileId,
$skill->getId(),
$skill->level
);
/*Since I do a roll-back inside my controller in case something goes wrong.
I decided to add the flush here.
As far no additional checks where needed in my case
since I require a Profile instance and a Skill instance inside the Profile entity.*/
EntityManager::persist($profileSkill);
EntityManager::flush();
}
The thing with many-to-many relationships is that any additional columns other than two primary keys from both tables are considered pivot columns, when attaching entities to such relationships you want to use the method attach which accepts array of ids as first parameter and an array with pivot columns, take the following into consideration.
public function addSkill(Skill $skill)
{
if ($this->skills->contains($skill)) {
return;
}
//Dunno what this method does
return $this->skills->add($skill);
//But this is the correct way of adding a skill
$this->skills->attach($skill->id, ['level' => $skill->level]);
}
Hope this can clarify few things even though Eloquent was used as an example; here is the manual link for the above code.

Symfony3 form checkbox save error

I tried to look up on Google but didn't find anyone with such a problem. I think I did everything like the documentation guides but I guess I'm missing something
So I have a form with checkbox like this:
$builder->add(
'productTypes',
EntityType::class,
array(
'label' => 'Available for products',
'class' => 'ShopBundle:ProductType',
'choice_label' => 'name',
'multiple' => true,
'expanded' => true,
'by_reference' => false,
)
);
When I'm editing everything goes smooth, I can edit existing entry and check or uncheck this checkbox, it saves properly, but when I try to add new Object I get error:
PHP Fatal error: Call to a member function add() on null in
C:\xampp\htdocs\uniacar-sf\src\ShopBundle\Entity\ProductAttribute.php
on line 188
This is my controller action:
public function editAction(Request $request, $id = null)
{
$this->setMenuTab('cars', 'admin');
$productTypes = new ArrayCollection();
if (!empty($id)) {
$attribute = $this->getRepo(ProductAttribute::class)->find($id);
$this->setTitle('admin.cars.attributes.edit');
foreach ($attribute->getProductTypes() as $value) {
$productTypes->add($value);
}
} else {
$attribute = new ProductAttribute();
$this->setTitle('admin.cars.attributes.new');
}
$form = $this->createForm(ProductAttributeForm::class, $attribute);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$attribute = $form->getData();
foreach ($productTypes as $productType) {
if (false === $attribute->getProductTypes()->contains($productType)) {
$productType->getAttributes()->removeElement($attribute);
$this->db()->persist($productType);
}
}
$this->db()->persist($attribute);
$this->db()->flush();
return $this->redirectToRoute('carAdmin', array('tab' => 'attributes'));
}
$this->setVariables(
array(
'form' => $form->createView(),
'attribute' => $attribute,
)
);
return $this->response();
}
$this->db() is my shortcut for $this->getDoctrine()->getManager()
And this is definition part of ProductAttribute that relates to ProductType:
/**
* Constructor
*/
public function __construct() {
$this->productTypes = new ArrayCollection();
}
/**
* Many Attributes have Many ProductTypes
* #ORM\ManyToMany(targetEntity="ProductType", mappedBy="attributes", cascade={"persist"})
*/
private $productTypes;
/**
* #param ProductType $productType
*/
public function addProductType(ProductType $productType)
{
$this->productTypes->add($productType);
$productType->addProductAttribute($this);
}
/**
* #param ProductType $productType
*/
public function removeProductType(ProductType $productType)
{
$this->productTypes->removeElement($productType);
}
Also there is part of ProductType Entity that relates to ProductAttribute:
/**
* Constructor
*/
public function __construct() {
$this->attributes = new ArrayCollection();
}
/**
* Many ProductTypes have Many Attributes
* #ORM\ManyToMany(targetEntity="ProductAttribute", inversedBy="productTypes")
* #ORM\JoinTable(name="product_type_to_attribute")
*/
private $attributes;
/**
* #param ProductAttribute $attribute
*/
public function addProductAttribute(ProductAttribute $attribute)
{
if (!$this->attributes->contains($attribute)) {
$this->attributes->add($attribute);
}
}
public function removeProductAttribute(ProductAttribute $attribute)
{
$this->attributes->removeElement($attribute);
}
I tried to follow Symfony Embed Form Tutorial (How to Embed a Collection of Forms)
I know that in this case there is no embeded collection (I have another field in this Entity, that is embeded collection of forms and it works just fine) but from what I understand relations are the same in this case, it's many to many so I have to tell the Symfony how to treat relations, add and remove objects.
I dumped data that comes in POST but it's the same as for edition - productType is there. Any ideas why do I get this error?
It fires in ProductAttribute Entity in the line $this->productTypes->add($productType);
EDIT:
I updated the controller code, I messed up the logic about unlinking ProductType from ProductAttribute. But it doesn't have any impact on the problem, still the same 500 error when I try to save new object.
EDIT2:
I can't get stack trace from Symfony because I get ordinary browser 500 error (probably because it's Fatal Error, I found it in apache logs). The line in controller which creates error is $form->handleRequest($request);.
This is not a Collection of Forms, but you are using collection specific method, this is not a good practice, however, you don't need this below code when you create a new object.
foreach ($productTypes as $value) {
if (false === $attribute->getProductTypes()->contains($value)) {
$attribute->getProductTypes()->removeElement($value);
}
}
So, I haven't found solution to the problem but I solved it somehow by fixing file structure of my project (moved bundle's Resources from general Resources folder to Bundle's Resources folder). I have no idea why this fixed the issue and what is even the connection between working but not proper folder structure and submitting forms but now it works, so I will mark the question as answered.

How to add sortable column for member list in Silverstripe admin?

I am struggling to add sort functionality on one of my member summary fields in admin.
I have extended the Silverstripe member class using:
class MyMemberExtension extends DataExtension
I have added a few fields to the default gridfield in admin:
private static $db = array(
'Organisation' => 'Varchar(100)'
);
private static $summary_fields = array(
'FirstName' => 'First Name',
'Surname' => 'Surname',
'Email' => 'Email',
'OrganisationName' => 'Organisation Name',
'LastVisited' => 'Last Visited',
'NumVisit' => 'Num Visits'
);
private static $casting = array(
'OrganisationName' => 'Varchar(100)'
);
public function getOrganisationName() {
return $this->owner->Organisation;
}
...and that all works nicely.
However, only the core fields like LastVisited are giving me sort arrows on the column headers.
I'm currently stuck as to how to implement the sort on my Organisation field. I tried adding :
public function getCMSFields()
{
$fields = parent::getCMSFields();
$grid = $fields->dataFieldByName('Organisation');
$gridConfig = $grid->getConfig();
$gridConfig->addComponent(new GridFieldSortableHeader());
return $fields;
}
public function getEditForm($id = null, $fields = null) {
$form=parent::getEditForm($id, $fields);
$model = singleton($this->modelClass);
// add sorting if we have a field for...
if (class_exists('GridFieldSortableRows')
&& $model->hasField('Organisation')
&& $gridField=$form->Fields()->dataFieldByName($this->sanitiseClassName($this->modelClass))) {
if($gridField instanceof GridField) {
$gridField->getConfig()->addComponent(new GridFieldSortableRows('Organisation'));
}
}
return $form;
}
...to my class, but I'm not convinced these are even being called, as even if I just return null from these two functions nothing changes.
I have found a few answers that deal with extensions to ModelAdmin, but not for the core Member list. Thanks!
First of all, I'm not sure why you chose to have a getter named OrganisationName, where you could just as well use Organisation directly? That being said, I think your question is valid and might apply to different scenarios and/or field-types.
The Form-field that is being used to edit members is the Members GridField within SecurityAdmin. Luckily, there's an extension hook (updateEditForm) to modify the form fields of SecurityAdmin.
So in order to modify the sorting of the Members GridField, create an Extension like the following:
<?php
class MemberAdminExtension extends Extension
{
public function updateEditForm(Form $form)
{
/** #var GridField $memberGridField */
if ($memberGridField = $form->Fields()->dataFieldByName('Members')) {
/** #var GridFieldSortableHeader $sortHeader */
if ($sortHeader = $memberGridField->getConfig()->getComponentByType('GridFieldSortableHeader')) {
// Map OrganisationName to the Organisation field
$sortHeader->setFieldSorting([
'OrganisationName' => 'Organisation'
]);
}
}
}
}
And apply the extension via config to SecurityAdmin:
# Within _config/config.yml
SecurityAdmin:
extensions:
- MemberAdminExtension
After a dev/build your Member table should be sortable by Organisation Name as well…

OctoberCMS Builder plugin with state and suburb

I have created two plugins (States and Suburbs) using Builder plugin and so far it works great.
The Thing is, in States plugin, I am simply allowing ability to add state names and in Suburbs plugin, I am allowing users to select State first and then enter suburb name. All works fine as of now in these two plugins.
Now the thing is, I have a third plugin called as Properties in which I have both these 2 drop-downs State and Suburb but as of now All States and All Suburbs are showing. But I want users to select first State and then based on state selection it should should all its suburbs to my another Suburb drop-down.
I have tried to use dependsOn which Builder plugin provides but I just am not able to understand the flow to achieve it step by step based on the current scenario I have. Below is the code what I have done and tried so far.
plugins\technobrave\properties\models\Property.php
<?php namespace Technobrave\Properties\Models;
use Model;
use technobrave\states\Models\State as State;
use technobrave\suburbs\Models\Suburb as Suburb;
public function getStateIdOptions()
{
// getting all states
$get_all_states = State::all();
$fields[''] = 'Select any State';
foreach ($get_all_states as $current_state) {
$fields[$current_state->attributes['id']] = $current_state->attributes['state_name'];
}
ksort($fields);
return $fields;
}
public function getSuburbIdOptions($stateId)
{
// getting all suburbs
$get_all_suburbs = Suburb::all();
$fields[''] = 'Select any Suburb';
foreach ($get_all_suburbs as $current_suburb) {
$fields[$current_suburb->attributes['id']] = $current_suburb->attributes['suburb'];
}
ksort($fields);
return $fields;
}
}
How can I do this from here on ? Any help or guidance will be highly appreciated and useful.
Thanks
Ok Guys,
Eventually I have come up with a solution. Here is what I have done.
fields.yaml File: technobrave\properties\models\property\fields.yaml
state_id:
label: 'State:'
span: auto
required: 1
type: dropdown
tab: 'Address Information'
suburb_id:
label: 'Suburb:'
span: auto
required: 1
type: dropdown
tab: 'Address Information'
placeholder: 'Select any Suburb'
dependsOn: state_id
As you can see above,
In suburb_id I have added, below two lines of code.
placeholder: 'Select any Suburb'
dependsOn: state_id
Property Model File: technobrave\properties\models\Property.php
use Model;
use technobrave\states\Models\State as State;
use technobrave\suburbs\Models\Suburb as Suburb;
public function getStateIdOptions()
{
// getting all states
$get_all_states = State::all();
$fields[''] = 'Select any State';
foreach ($get_all_states as $current_state) {
$fields[$current_state->attributes['id']] = $current_state->attributes['state_name'];
}
ksort($fields);
return $fields;
}
public function getSuburbIdOptions()
{
return Suburb::getNameList($this->state_id);
}
Here above, I have just updated getSuburbIdOptions method with below code and removed my old code.
return Suburb::getNameList($this->state_id);
Then I went to my Suburbs plugin.
Suburb Model File: technobrave\suburbs\models\Suburb.php
And in this model file, I have made sure to use belongsTo and added getNameList method like below.
<?php namespace Technobrave\Suburbs\Models;
use Model;
use technobrave\states\Models\State as State;
/**
* Model
*/
class Suburb extends Model
{
/**
* #var string The database table used by the model.
*/
public $table = 'youtable_here_';
public $belongsTo = ['State' => [
'technobrave\states\Models\State',
'key' => 'state'
],
];
/**
* #var array Cache for nameList() method
*/
protected static $nameList = [];
public static function getNameList($stateId)
{
if (isset(self::$nameList[$stateId])) {
return self::$nameList[$stateId];
}
return self::$nameList[$stateId] = self::wherestate($stateId)->lists('suburb', 'id');
}
}
And it works.
Hope it will help to those who stuck on the same issue/implementation.
Thanks

Symfony form not saving entity with ManyToMany relation

I have problem saving entity trough form with ManyToMany relations.
I can not save fields that are on "mappedBy" side of relation.
Code below is not saving anything to database and not trowing any errors:
// Entity/Pet
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Customer", mappedBy="pet", cascade={"persist"})
*/
private $customer;
/**
* Set customer
*
* #param \AppBundle\Entity\Customer $customer
* #return Pet
*/
public function setCustomer($customer)
{
$this->customer = $customer;
return $this;
}
// Entity/Customer
/**
* #var Pet
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Pet", inversedBy="customer", cascade={"persist"})
* #ORM\JoinTable(name="customer_pet",
* joinColumns={
* #ORM\JoinColumn(name="customer_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="pet_id", referencedColumnName="id")
* }
* )
*/
private $pet;
// PetType.php
$builder->add('customer', 'entity',
array(
'class' => 'AppBundle:Customer',
'property' => 'firstname',
'empty_value' => 'Choose owner',
'multiple' => true
));
It is working the other way around. So if I am saving something from CustomerType everything works.
EDIT:
Solution below worked for me but after couple days I found a problem with that solution. If form will be submitted with value that has been already saved in the database then Symfony will trow an error. To prevent that I had to check if given customer has been already assigned to the pet.
Checking of currently assigned customers had to be done on the beginning of function and not after form submission because for some reason after submission Pet() object contains submitted values not only those present in the db.
So on the beginning I've putted all already assigned customers in to the array
$em = $this->getDoctrine()->getManager();
$pet = $em->getRepository('AppBundle:Pet')->find($id);
$petOriginalOwners = array();
foreach ($pet->getCustomer() as $petCustomer)
{
$petOriginalOwners[] = $petCustomer->getId();
}
And after form submission I've checked if submitted ID's are in the array
if ($form->isValid())
{
foreach ($form['customer']->getData()->getValues() as $v)
{
$customer = $em->getRepository('AppBundle:Customer')->find($v->getId());
if ($customer && !in_array($v->getId(), $petOriginalOwners) )
{
$customer->addPet($pet);
}
}
$em->persist($pet);
$em->flush();
return $this->redirect($this->generateUrl('path'));
}
In Symfony2 the entity with the property with the inversedBy doctrine comment is the one that is supposed to EDIT THE EXTRA TABLE CREATED BY THE MANYTOMANY RELATION. That is why when you create a customer it inserts the corresponding rows in that extra table, saving the corresponding pets.
If you want the same behavior to happen the other way around, I recommend:
//PetController.php
public function createAction(Request $request) {
$entity = new Pet();
$form = $this->createCreateForm($entity);
$form->submit($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
foreach ($form['customer']->getData()->getValues() as $v) {
$customer = $em->getRepository('AppBundle:Customer')->find($v->getId());
if ($customer) {
$customer->addPet($entity);
}
}
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('pet_show', array('id' => $entity->getId())));
}
return $this->render('AppBundle:pet:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
private function createCreateForm(Pet $entity) {
$form = $this->createForm(new PetType(), $entity, array(
'action' => $this->generateUrl('pet_create'),
'method' => 'POST',
));
return $form;
}
These two are but standard Symfony2 CRUD-generated actions in the controller corresponding to Pet entity.
The only tweak is the foreach structure inserted in the first action, that way you forcibly add the same pet to each customer you select in the form, thus getting the desired behavior.
Look, it is highly probable THIS is not the RIGHT WAY, or the PROPER WAY, but is A WAY and it works. Hope it helps.
In my case with a services <-> projects scenario, where services has "inversedBy" and projects has "mappedBy" I had to do this in my project controller's edit action so that when editing a project the services you checked would be persisted.
public function editAction(Request $request, Project $project = null)
{
// Check entity exists blurb, and get it from the repository, if you're inputting an entity ID instead of object ...
// << Many-to-many mappedBy hack
$servicesOriginal = new ArrayCollection();
foreach ($project->getServices() as $service) {
$servicesOriginal->add($service);
}
// >> Many-to-many mappedBy hack
$form = $this->createForm(ProjectType::class, $project);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
// << Many-to-many mappedBy hack
foreach ($servicesOriginal as $service) {
if (!$project->getServices()->contains($service)) {
$service->removeProject($project);
$em->persist($service);
}
}
foreach ($project->getServices() as $service) {
$service->addProject($project);
$em->persist($service);
}
// >> Many-to-many mappedBy hack
$em->persist($project);
$em->flush();
return; // I have a custom `redirectWithMessage()` here, use what you like ...
}
return $this->render("Your-template", [
$form => $form->createView(),
$project => $project,
]);
}
This works for both adding and removing entities in the many-to-many from the "mappedBy" side, so EntityType inputs should work as intended.
What's going on here is we're first building an "original" collection containing all of the service entities already linked to for this project. Then when the form is saving we're ensuring:
First that any unchecked services (those in the original collection but not the project object) have the project removed from their internal collection, then persisted.
Second that any newly checked services each add the project to their internal collection, then persisted.
Important: This depends on your entity's addService() and addProject() methods respectively check that each others' collections do not contain duplications. If you don't do this you'll end up with an SQL level error about a duplicate record insertion.
In the service entity I have:
/**
* Add project
*
* #param Project $project
*
* #return Service
*/
public function addProject(Project $project)
{
if (!$this->projects->contains($project)) {
$this->projects->add($project);
}
if (!$project->getServices()->contains($this)) {
$project->getServices()->add($this);
}
return $this;
}
In the project entity I have:
/**
* Add service
*
* #param Service $service
*
* #return Project
*/
public function addService(Service $service)
{
if (!$this->services->contains($service)) {
$this->services->add($service);
}
if (!$service->getProjects()->contains($this)) {
$service->getProjects()->add($this);
}
return $this;
}
You could alternatively check this in your controller instead, but makes sense if the model validates this itself when possible, as the model would break anyway if there were duplicates from any source.
Finally in your controller's create action you'll likely need this bit too just before $em->persist($project). (You won't need to work with an "original" collection as none will exist yet.)
// << Many-to-many mappedBy hack
foreach ($project->getServices() as $service) {
$service->addProject($project);
$em->persist($service);
}
// >> Many-to-many mappedBy hack
I just had the same problem and I solved it differently.
Changing the code in the controller is not the better way to do it.
In my case I have a GenericController that handle all my CRUDs so I can't put in it specific code.
The best way to do it is by adding in your PetType a listener like this :
// PetType.php
$builder->add('customer', 'entity',
array(
'class' => 'AppBundle:Customer',
'property' => 'firstname',
'empty_value' => 'Choose owner',
'multiple' => true
))
->addEventListener( FormEvents::SUBMIT, function( FormEvent $event ) {
/** #var Pet $pet */
$pet = $event->getData();
foreach ( $pet->getCustomers() as $customer ) {
$customer->addPet( $pet );
}
} );
That way you'll keep the mapping logic in the same place.

Categories