Edit form returns null value Symfony2 - symfony

I have an Edit Form in my application and when tries to save (insert) the new record I get this error message:
An exception occurred while executing 'INSERT INTO in_orden_compra_detalle (id_orden_compra, id_producto, cantidad, precio_compra, total, entrega, fecha_entrega) VALUES (?, ?, ?, ?, ?, ?, ?)' with params [null, null, 89, 45, null, null, null]:
Table in_orden_compra_detalle is related to 2 tables (in_producto and in_orden_compra)
Here my relatioship:
class InOrdenCompra
{
/**
* #ORM\ManyToOne(targetEntity="InProveedor", inversedBy="InOrdenCompra")
* #ORM\JoinColumn(name="id_proveedor", referencedColumnName="id")
*/
protected $proveedorOc;
/**
* #ORM\ManyToOne(targetEntity="Nival\AccesoBundle\Entity\AdUsuario", inversedBy="InOrdenCompra")
* #ORM\JoinColumn(name="id_usuario", referencedColumnName="id_usuario")
*/
/**
* #ORM\OneToMany(targetEntity="InOrdenCompraDetalle", mappedBy="InOrdenCompra", cascade={"persist"})
*/
protected $ordenCompra;
class InProducto
{
/**
* #ORM\OneToMany(targetEntity="InOrdenCompraDetalle", mappedBy="InProducto", cascade={"persist"})
*/
protected $productoOc;
public function __construct()
{
$this->productoOc = new ArrayCollection();
}
public function __toString() {
return $this->nombre;
}
class InOrdenCompraDetalle
{
/**
* #ORM\ManyToOne(targetEntity="InOrdenCompra", inversedBy="InOrdenCompraDetalle")
* #ORM\JoinColumn(name="id_orden_compra", referencedColumnName="id")
*/
protected $ordenCompra;
/**
* #ORM\ManyToOne(targetEntity="InProducto", inversedBy="InOrdenCompraDetalle")
* #ORM\JoinColumn(name="id_producto", referencedColumnName="id_producto")
*/
protected $productoOc;
My Controller for new record:
public function newAction($id_orden_compra)
{
$entity = new InOrdenCompraDetalle();
$entity->setOrdenCompra($this->get('doctrine')->getRepository('NivalInventarioBundle:InOrdenCompra')->find($id_orden_compra));
$form = $this->createCreateForm($entity, $id_orden_compra);
return $this->render('NivalInventarioBundle:InOrdenCompraDetalle:new.html.twig', array(
'id_orden_compra' => $id_orden_compra,
'entity' => $entity,
'form' => $form->createView(),
));
}
I need to pass the id_orden_compra value to setOrdenCompra in entity InOrdenCompraDetalle.
Also id_producto should have the value selected from entity field:
->add('productoOc', 'entity', array(
'class' => 'NivalInventarioBundle:InProducto',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.nombre', 'ASC');
},
'choice_label' => function ($displayname) {
return $displayname->getDisplayName();},
'by_reference' => true,
'expanded' => false,
'placeholder' => 'Seleccione una opción',
'mapped' => true,
'multiple' => false,
))
->add('cantidad')
->add('precioCompra')
But also comes null.
Please help
UPDATED
public function createAction(Request $request, $id_orden_compra)
{
$entity = new InOrdenCompraDetalle();
$form = $this->createCreateForm($entity, $id_orden_compra);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('inordencompradetalle_show', array('id_orden_compra' => $id_orden_compra, 'id' => $entity->getId())));
}
return $this->render('NivalInventarioBundle:InOrdenCompraDetalle:new.html.twig', array(
'id_orden_compra' => $id_orden_compra,
'entity' => $entity,
'form' => $form->createView(),
));
}
createCreateForm:
private function createCreateForm(InOrdenCompraDetalle $entity, $id_orden_compra)
{
$form = $this->createForm(new InOrdenCompraDetalleType(), $entity, array(
'action' => $this->generateUrl('inordencompradetalle_create', array('id_orden_compra' => $id_orden_compra)),
'method' => 'POST',
));
return $form;
}

Related

Symfony2 Cannot instantiate interface Doctrine\Common\Collections\Collection

Symfony version 2.8
I have a problem when I try to add new Collection(); in construct function of User Entity.
public function __construct()
{
$this->sectors = new Collection();
parent::__construct();
}
Sector has many to many relationship
/**
* #ORM\ManyToMany(targetEntity="UserBundle\Entity\Sectors", fetch="EAGER")
* #ORM\JoinTable(
* joinColumns={#ORM\JoinColumn(onDelete="CASCADE")},
* inverseJoinColumns={#ORM\JoinColumn(onDelete="CASCADE")}
* )
*/
public $sectors;
and getter/setter methods are
/**
* Add sector
*
* #param UserBundle\Entity\Sectors $sector
*
* #return User
*/
public function addSector(UserBundle\Entity\Sectors $sector)
{
$this->sectors[] = $sector;
return $this;
}
/**
* Remove sector
*
* #param UserBundle\Entity\Sectors $sector
*/
public function removeSector(UserBundle\Entity\Sectors $sector)
{
$this->sectors->removeElement($sector);
}
/**
* Get sectors
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getSectors()
{
return $this->sectors;
}
When in a FormType I do:
$builder
->add('sectors', EntityType::class, array(
'class' => 'UserBundle\Entity\Sectors',
'placeholder' => 'Select Sector ...',
'label' => 'Sector',
'required' => false,
'attr' => ['placeholder' => 'Select Sector ...', 'data-jcf' => '{"wrapNative": false, "wrapNativeOnMobile": false, "useCustomScroll": true, "multipleCompactStyle": true}'],
'multiple' => true,
'expanded' => false,
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.name', 'ASC');
},
));
$formModify = function (FormInterface $form, \Doctrine\Common\Collections\ArrayCollection $sector, $factory) {
$output = [];
foreach($sector as $sec) {
$output[] = $sec->id;
}
$formOption = array(
'class' => 'UserBundle\Entity\UserAccreditation',
'multiple' => true,
'auto_initialize' => false,
'required' => false,
'expanded' => true,
'choice_attr' => function ($output) {
return ['class' => 'attr_checkbox'];
},
'query_builder' => function(EntityRepository $ertt) use ($output) {
$qb = $ertt->createQueryBuilder('g');
$qb->select(array('g'));
$qb->where('g.sector IN (:sector_id)');
$qb->setParameters( array('sector_id' => $output) );
$qb->orderBy('g.name', 'ASC');
return $qb;
},
);
$form->add($factory->createNamed('accreditationdata', EntityType::class, null, $formOption));
};
$builder->addEventListener(FormEvents::PRE_SET_DATA,function (FormEvent $event) use ($formModify,$factory) {
$data = $event->getData();
$form = $event->getForm();
if ($data != null) {
//print_r(get_object_vars($data->getSectors()));
$formModify($event->getForm(), $data->getSectors(),$factory);
}
}
);
$factory = $builder->getFormFactory();
$builder->get('sectors')->addEventListener(FormEvents::POST_SUBMIT,function (FormEvent $event) use ($formModify,$factory) {
$sector = $event->getForm()->getData();
//print_r($sector);
$formModify($event->getForm()->getParent(), $sector,$factory);
}
);
I get following error:
Fatal error: Cannot instantiate interface Doctrine\Common\Collections\Collection
Earlier I am using ArrayCollection instead of Collection, I have to do this because I am getting error
Type error: Argument 2 passed to UserBundle\Form\Type\ProfileAboutMeFormType::UserBundle\Form\Type{closure}() must be an instance of Doctrine\Common\Collections\ArrayCollection, instance of Doctrine\ORM\PersistentCollection given,
and by searching on google I found this solution on github link
https://github.com/doctrine/orm/issues/5946
but still I am facing the problem. can anyone tell me What goes wrong here ?

Symfony: Creating a new user results in overwriting of properties

When someone creates a new user on our application, some of his own properties get overwritten by the new users properties. I have no clue yet, where to look for the mistake, since in the controller or entities, nothing was changed.
Here are some information: the user entity (we are using the FOS User Bundle)
class User extends BaseUser{
/**
* #Solr\Id
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #Solr\Field(type="string")
* #Assert\NotBlank()
* #var string
* #ORM\Column(type="string", length=32, nullable=false)
*/
protected $firstName;
/**
* #Solr\Field(type="string")
* #Assert\NotBlank()
* #var string
* #ORM\Column(type="string", length=32, nullable=false)
*/
protected $lastName;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Agency", inversedBy="useragencies", cascade={"persist"})
* #ORM\JoinTable(name="user_user_agencies",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="iata8", referencedColumnName="iata8")})
* #var \AppBundle\Entity\Agency
**/
private $agencies;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Product", inversedBy="users", cascade={"persist"})
* #ORM\JoinTable(name="user_user_products",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="product_id", referencedColumnName="id")})
* #var \AppBundle\Entity\Product
**/
private $products;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Market", inversedBy="users", cascade={"persist"})
* #ORM\JoinTable(name="user_user_markets",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="market_id", referencedColumnName="id")})
* #var \AppBundle\Entity\Market
* #Solr\Field(type="string", getter="getId")
**/
private $markets;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Airline", inversedBy="users", cascade={"persist"})
* #ORM\JoinTable(name="user_user_airlines",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="airline_id", referencedColumnName="id")})
* #var \AppBundle\Entity\Airline
* #Solr\Field(type="string", getter="getId")
**/
private $airlines;
...
The properties that get overwritten are products and airlines. There is no prePersist() or preUpdate() function for this entity!
The create controller
class CreateController extends Controller
{
/**
* #Security("has_role('ROLE_USER_INVITER')")
* #Route("/user/create/{employer}", defaults={"employer": 1}
* , requirements={"employer": "\d+"}, name="userBundle_create")
*/
public function createAction($employer, Request $request)
{
$currentUser=$this->container->get('security.token_storage')->getToken()->getUser();
// get employer Object
$em = $this->getDoctrine ()->getManager ();
$repository = $this->getDoctrine()
->getRepository('UserBundle:Employer');
$employerObj = $repository->findOneByIdInContext($employer, $currentUser);
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->createUser();
$url = $this->get('router')->generate('userBundle_create', array(
'employer' => $employerObj->getId()
));
// generate form and handle
$form = $this->createForm(CreateType::class, $user
, array('employer' => $employerObj,
'action' => $url,)
);
$form->handleRequest($request);
if ($form->isValid()) {
$tokenGenerator = $this->container->get('fos_user.util.token_generator');
$user->setConfirmationToken($tokenGenerator->generateToken());
$user->setUsername($user->getEmail());
$user->setEnabled(false);
$user->setApprover($currentUser);
$user->setInviter($currentUser);
$user->addRole($user->getMainRole()->getName());
$userManager->updateUser($user);
if(count($user->getAgencies()) > 0){
$userId = rtrim($user->getId(),"_user");
$query = $em->createQuery("SELECT DISTINCT (a.market) FROM UserBundle\Entity\User u JOIN u.agencies a WHERE u.id = $userId");
$marketIds = $query->getResult();
$em = $this->getDoctrine ()->getManager ();
$repository = $this->getDoctrine()
->getRepository('AppBundle:Market');
$markets = $repository->findOneById($marketIds[0]);
$user->addMarket($markets);
$userManager->updateUser($user);
}
$this->addFlash(
'success',
'The user was created and an activation email was sent!'
);
return $this->redirectToRoute('userBundle_list');
}
return $this->render('UserBundle:User:create.html.twig', array(
'form' => $form->createView(),
'user'=>$user,
));
}
}
Here are more classes that may be useful for helping to point me in the right direction.
CreateType
class CreateType extends AbstractType
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => User::class,
'employer' => null
));
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$employer = $options['employer'];
$builder
->add('firstName', 'text', array('label' => 'label.firstname',
'translation_domain' => 'User',))
->add('lastName', 'text', array('label' => 'label.lastname',
'translation_domain' => 'User',))
;
$user = $this->tokenStorage->getToken()->getUser();
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($user, $employer){
$form = $event->getForm();
// show iata selection if empoyer is any agency
$employerArr = array(10, 11);
if (in_array($employer->getId(), $employerArr)) {
// only show iata based on user's employer
if($user->hasRoles(array('ROLE_AGENCY_TC_ONLY',
'ROLE_AGENCY_WAIVER_REQUEST_ONLY',
'ROLE_AGENCY_CORE_TEAM',
'ROLE_AGENCY',
'ROLE_AGENCY_MANAGEMENT',
'ROLE_AGENCY_SIGNEE','ROLE_CORPORATION_TRAVEL_MANAGER' ))){
$form
->add('agencies', EntityType::class, array(
'class' => 'AppBundle:Agency',
'query_builder' => function (EntityRepository $er) use ($user) {
return $er->createQueryBuilder('a')
->addOrderBy('a.id', 'ASC')
->andWhere('a.id IN (:ids)')
->setParameter('ids',$user->getAgencies());
},
'choice_label' => 'agencyName',
// 'data' => $user->getAgencies(),
'label' => 'label.iata',
'empty_value' => "label.select.agency",
'property' => 'id',
'expanded' => false, 'multiple' => true,
'required' => true,
'translation_domain' => 'User',
'choice_translation_domain' => 'User'));
} else {
// only show iata based on user's context
$form
->add('agencies', EntityType::class, array(
'class' => 'AppBundle:Agency',
'query_builder' => function (EntityRepository $er) use ($user) {
return $er->createQueryBuilder('a')
->addOrderBy('a.id', 'ASC')
->andWhere('a.market IN (:markets)')
->setParameter('markets',$user->getMarkets());
},
'choice_label' => 'agencyName',
'label' => 'label.iata',
'empty_value' => "label.select.agency",
'property' => 'id',
'expanded' => false, 'multiple' => true,
'required' => true,
'translation_domain' => 'User',
'choice_translation_domain' => 'User'));
}
// show market only if not agency user
} else {
// only show specific markets based on user's context
$form->add('markets', 'entity', array(
'class' => 'AppBundle:Market', 'property' => 'id',
'query_builder' => function (EntityRepository $er) use ($user) {
$markets = $user->getMarkets();
return $er->createQueryBuilder('m')
->addOrderBy('m.id', 'ASC')
->andWhere('m.id IN (?1)')
->setParameter(1,$markets);
},
// 'choice_value' => 'id',
'choice_label' => 'id', 'label' => 'label.markets',
'translation_domain' => 'User',
'expanded' => false, 'multiple' => true,));
}
// only show specific roles based on user's employer
$form->add('mainRole', 'entity', array(
'class' => 'UserBundle:Role',
'query_builder' => function (EntityRepository $er) use ($employer){
$roles = $employer->getRoles();
return $er->createQueryBuilder('r')
->orderBy('r.sort', 'ASC')
->andWhere('r.id IN (?1)')
->setParameter(1,$roles);
},
'choice_label' => 'translationKey',
'choices_as_values' => true, 'label' => 'label.role',
'expanded' => true, 'multiple' => false,
'translation_domain' => 'User',
'choice_translation_domain' => 'Role',));
// only show specific airlines based on user's context
$form->add('airlines', 'entity', array(
'class' => 'AppBundle:Airline', 'property' => 'id',
'query_builder' => function (EntityRepository $er) use ($user) {
$airlines = $user->getAirlines();
return $er->createQueryBuilder('a')
->addOrderBy('a.id', 'ASC')
->andWhere('a.id IN (?1)')
->setParameter(1,$airlines);
},
'choice_value' => 'id',
'data' => $user->getAirlines(),
'choice_label' => 'id', 'label' => 'label.airlines',
'translation_domain' => 'User',
'expanded' => false, 'multiple' => true,));
// only show specific products based on user's context
$form->add('products', 'entity', array(
'class' => 'AppBundle:Product', 'property' => 'id',
'query_builder' => function (EntityRepository $er) use ($user) {
$products = $user->getProducts();
return $er->createQueryBuilder('p')
->addOrderBy('p.id', 'ASC')
->andWhere('p.id IN (?1)')
->setParameter(1,$products);
},
'choice_value' => 'id',
'data' => $user->getProducts(),
'choice_label' => 'translationKey', 'label' => 'label.products',
'translation_domain' => 'User',
'expanded' => false, 'multiple' => true,
'choice_translation_domain' => 'AppBundle',));
});
}
public function getParent()
{
return 'FOS\UserBundle\Form\Type\RegistrationFormType';
}
public function getBlockPrefix()
{
return 'userBundle_create';
}
}
Your issue is caused by these to lines:
'data' => $user->getAirlines(),
and
'data' => $user->getProducts(),
To change the new user s airlines & products collection, symfony form uses the loggedin users airlines & products collection reference.
Clone the collection when setting it as default, to remove the reference to the logged in user.
'data' => clone $user->getAirlines(),
and
'data' => clone $user->getProducts(),
Hope it helps.
Wrong assumption: Your error is in CreateType class. You use the loggedin user s properties to populate agencies, airlines and products fields of your form:
$user = $this->tokenStorage->getToken()->getUser();
...
'query_builder' => function (EntityRepository $er) use ($user) {
You should instead use the user you edit. Add in your buildForm function:
$userEdited = $builder->getData();
and then change:
'query_builder' => function (EntityRepository $er) use ($userEdited) {
in all places.
Do not forget to change also:
$user->getMarkets()
to
$userEdited->getMarkets()
in your callbacks, same for ailines & products.

How to set a value for entity field in a form? Symfony2

I have 3 tables realated, inProducto, inProveedor and InProveedorProducto, here my relashionship:
inProveedorProducto:
class InProveedorProducto
{
/**
* #ORM\ManyToOne(targetEntity="InProducto", inversedBy="InProveedorProducto")
* #ORM\JoinColumn(name="id_producto", referencedColumnName="id_producto")
*/
protected $producto;
/**
* #ORM\ManyToOne(targetEntity="InProveedor", inversedBy="InProveedorProducto")
* #ORM\JoinColumn(name="id_proveedor", referencedColumnName="id")
*/
protected $proveedor;
InProveedor:
class InProveedor
{
/**
* #ORM\OneToMany(targetEntity="InProveedorProducto", mappedBy="InProveedor", cascade={"persist"})
*/
protected $proveedorProducto;
public function __construct()
{
$this->proveedorProducto = new ArrayCollection();
}
And InProducto:
class InProducto
{
/**
* #ORM\OneToMany(targetEntity="InProveedorProducto", mappedBy="InProducto", cascade={"persist"})
*/
protected $producto;
public function __construct()
{
$this->producto = new ArrayCollection();
}
My problem is that I have to open a new Form for inProveedorProducto, but idProveedor field should be automatic from prior selection of user.
My controller:
public function newAction()
{
$entity = new InProveedorProducto();
$form = $this->createCreateForm($entity);
$form->get('idProveedor')->setData(1);
return $this->render('NivalInventarioBundle:InProveedorProducto:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
When I open de form, the first field which is idProveedor appears filled out with the number 1.
THen we select the idProducto and put the price, but when try to create:
Error:
An exception occurred while executing 'INSERT INTO in_proveedor_producto (id_proveedor, id_producto, precio_compra) VALUES (?, ?, ?)' with params [null, 21, 1]:
It seems like idProveedor is comming NULL.
My inProveedorProducto type:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('idProveedor')
->add('producto', 'entity', array(
'class' => 'NivalInventarioBundle:InProducto',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.nombre', 'ASC');
},
'choice_label' => 'nombre',
'by_reference' => true,
'expanded' => false,
'placeholder' => 'Seleccione una opción',
'mapped' => true,
'multiple' => false
))
->add('precioCompra')
;
Please help me.
Regards,
Operate with a model, not with a form data.
public function newAction()
{
$entity = new InProveedorProducto();
$entity->setProveedor($this->get('doctrine')->getRepository('NivalInventarioBundle:InProveedor')->find(1));
$form = $this->createCreateForm($entity);
return $this->render('NivalInventarioBundle:InProveedorProducto:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
And then just
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('proveedor')
->add('producto')
->add('precioCompra')
;

On update don't update an entity replace it

I have a Branch entity that has an Address entity, one address can be link to many other types of entities, what I want to do is when I edit the Address in the Branch entity instead of editing the address with the new data I want to create a new Address entity and attach it to the Branch, what is happening right now is that its editing the address, the problem with this is that I have other entities linked to that address.
This is my form:
class MBBranchType extends AbstractType{
protected $em;
function __construct(EntityManager $em){
$this->em = $em;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('branchName')
->add('branchCode')
->add('destiny', 'entity', array(
'class' => 'ATRBundle:Destiny',
'empty_value' => '-- Seleccione --',
'mapped' => true,
'query_builder' => function(EntityRepository $er){
return $er->createQueryBuilder('d')
->orderBy('d.destinyDesc', 'ASC');
}))
->add('startOperation', 'text')
->add('stopOperation', 'text', array('required' => ''))
->add('authorizationL1', 'checkbox', array('required' => ''))
->add('authorizationL2', 'checkbox', array('required' => ''))
->add('authorizationL3', 'checkbox', array('required' => ''))
->add('address', new AddressType($this->em, new Address()), array('required' => ''))
->add('active', 'checkbox', array('required' => ''));
$builder->get('startOperation')->addModelTransformer(new StringToDateTransformer());
$builder->get('stopOperation')->addModelTransformer(new StringToDateTransformer());
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MB2\ATRBundle\Entity\MBBranch'
));
}
/**
* #return string
*/
public function getName()
{
return 'mb2_atr_mb_branch';
}
}
This is my Action
public function editMBBranchAction()
{
$id = $this->request->query->get('id');
$entity = $this->em->getRepository('ATRBundle:MBBranch')->find($id);
$form = $this->createForm(new MBBranchType($this->getDoctrine()->getManager()), $entity);
$form->handleRequest($this->request);
if ($form->isValid()) {
if($entity instanceof MBBranch){
$addressEntity = $this->em->getRepository('ATRBundle:Address')->findOneBy(
array('street'=>(string)$entity->getAddress()->getStreet()
, 'exteriorNum' => $entity->getAddress()->getExteriorNum();
, 'interiorNum' => $entity->getAddress()->getInteriorNum();
, 'settlment' => $entity->getAddress()->getSettlment()
)
);
if($addressEntity instanceof \MB2\ATRBundle\Entity\Address){
$entity->setAddress($addressEntity);
}else{
$otherAddress = new Address();
$otherAddress->setStreet($entity->getAddress()->getStreet());
$otherAddress->setExteriorNum($entity->getAddress()->getExteriorNum());
$otherAddress->setInteriorNum($entity->getAddress()->getInteriorNum());
$otherAddress->setSettlment($entity->getAddress()->getSettlment());
$entity->setAddress($otherAddress);
}
$this->em->flush();
}
return $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
}
return $this->render($this->entity['templates']['edit'], array(
'form' => $form->createView(),
'entity' => $entity,
));
}
As you can see it checks if the new Address entity exist, if it does exist it sets it on the $entity->setAddress($addressEntity);, If it does not exist it created a new Address() and sets the values, This does work, it created a new Address and saves it on the table, but for some reason it also updateing the old Address entity.
I found the solution
I added a $this->em->detach($entity->getAddress()); before attaching a new Address, please see example.
public function editMBBranchAction()
{
$id = $this->request->query->get('id');
$entity = $this->em->getRepository('ATRBundle:MBBranch')->find($id);
$form = $this->createForm(new MBBranchType($this->getDoctrine()->getManager()), $entity);
$form->handleRequest($this->request);
if ($form->isValid()) {
if($entity instanceof MBBranch){
$this->em->detach($entity->getAddress());
$addressEntity = $this->em->getRepository('ATRBundle:Address')->findOneBy(
array('street'=>(string)$entity->getAddress()->getStreet()
, 'exteriorNum' => $entity->getAddress()->getExteriorNum();
, 'interiorNum' => $entity->getAddress()->getInteriorNum();
, 'settlment' => $entity->getAddress()->getSettlment()
)
);
if($addressEntity instanceof \MB2\ATRBundle\Entity\Address){
$entity->setAddress($addressEntity);
}else{
$otherAddress = new Address();
$otherAddress->setStreet($entity->getAddress()->getStreet());
$otherAddress->setExteriorNum($entity->getAddress()->getExteriorNum());
$otherAddress->setInteriorNum($entity->getAddress()->getInteriorNum());
$otherAddress->setSettlment($entity->getAddress()->getSettlment());
$entity->setAddress($otherAddress);
}
$this->em->flush();
}
return $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
}
return $this->render($this->entity['templates']['edit'], array(
'form' => $form->createView(),
'entity' => $entity,
));
}

Controller - No access in class - Entity

I got this error message, but I don't really understand why.
Neither the property "categories" nor one of the methods "addCategory()"/"removeCategory()", "setCategories()", "categories()", "__set()" or "__call()" exist and have public access in class "Checkout\Bundle\ItemBundle\Entity\Item".
The thing is, in my entity "Item" I really have all of this stuff:
/**
* #ORM\ManyToMany(targetEntity="Checkout\Bundle\ItemBundle\Entity\Category", mappedBy="items")
**/
private $categories;
and
/**
* Add categories
*
* #param Category $categories
* #return Item
*/
public function addCategory(Category $categories)
{
$this->categories[] = $categories;
return $this;
}
/**
* Remove categories
*
* #param Category $categories
*/
public function removeCategory(Category $categories)
{
$this->categories->removeElement($categories);
}
/**
* Get categories
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCategories()
{
return $this->categories;
}
Okay, okay - and what is in my Controller?
/**
* Creates a new Item entity.
*
* #Route("/create", name="item_create")
* #param Request $request
* #return \Symfony\Component\HttpFoundation\Response
*/
public function createAction(Request $request)
{
$entity = new Item();
$currentUser = $this->getUser();
$form = $this->createFormBuilder($entity)
->add('name', null, array(
'label' => 'Item Name',
'required' => true,
))
->add('categories', 'entity', array(
'label' => 'Select a Category',
'required' => false,
'class' => 'CheckoutItemBundle:Category',
'property' => 'name',
'query_builder' => function (EntityRepository $er) use ($currentUser) {
return $er->createQueryBuilder('c')
->where('c.user = :user')
->setParameter('user', $currentUser);
},
))
->add('submit', 'submit', array('label' => 'Speichern'))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
}
return $this->render(
'CheckoutItemBundle:Item:create.html.twig',
array(
'entity' => 'entity',
'form' => $form->createView()
)
);
}
So, the big question is, why he say that he didn't find it, when it is obviously there. Any idea? Thank you in advance!
->add('categories', 'entity', array(
'label' => 'Select a Category',
'required' => false,
'class' => 'CheckoutItemBundle:Category',
'property' => 'name',
'multiple' => true,
'query_builder' => function (EntityRepository $er) use ($currentUser) {
return $er->createQueryBuilder('c')
->where('c.user = :user')
->setParameter('user', $currentUser);
},
))
You have a Many-To-Many relation, but your form expects a Many-To-One. To fix this behavior need to set multiple to true.

Resources