I'm building an API where a user can update an entity with a collection as part of it. This works fine if I use forms throughout, but I'm building up the API. My entity looks like this:
<?php
class MyEntity {
// ...
/**
* #ORM\OneToMany(targetEntity="TitleEntity", mappedBy="entityID", cascade={"persist"})
*/
protected $myTitles;
public function getMyTitles() {
return $this->myTitles;
}
public function setMyTitles($titles) {
foreach($titles as $key => $obj) { $obj->setEntity($this); }
$this->myTitles = $collection;
}
public function addMyTitle($obj) {
$obj->setEntity($this);
$this->myTitles[] = $obj;
}
public function removeMyTitle($obj) {
$this->myTitle->removeElement($obj);
}
}
The myTitles is an entity that has an ID, the ID of the entity it is attached to, and then a title.
For the API, I'm passing a JSON content body back as a PUT request for the MyEntity object, so I end up with an array of the titles, and I'm prepping them like this to bind to a form for validation:
$myTitles = array();
foreach($titles as $key => $title) {
$titleObj = new TitleEntity();
$titleObj->setTitle($title);
}
$myEntity->setTitles($titles);
but it complains with:
The form's view data is expected to be of type scalar, array or an instance of
\ArrayAccess, but is an instance of class stdClass. You can avoid this error by
setting the "data_class" option to "stdClass" or by adding a view
transformer that transforms an instance of class stdClass to scalar, array or
an instance of \ArrayAccess
It looks like this happens because I call getMyTitles() before I bind my entity to the form I'm using to validate against.
I'm binding to the form using an array:
$form = $this->createForm(new AddEntity(), $myEntity);
$data = array( // Set all my data );
$form->bind($data);
if($form->isValid() {
// ...
If I do the createForm() call first, and then add the titles afterward, I get this:
Call to a member function removeElement() on a non-object
which occurs inside removeMyTitle().
How do I handle this?
Edit
Here is the AddEntity() type:
<?php
class AddEntity extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', 'text')
->add('subheading', 'text')
->add('description', 'textarea')
->add('myTitles', 'collection', array(
'type' => new AddMyTitles(), // Basic type to allow setting the title for myTitle entities
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false,
'options' => array(
'required' => false,
),
));
}
public function getName()
{
return 'addEntity';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'My\TestBundle\Entity\Entity',
));
}
You need data transformers here.
http://symfony.com/doc/2.0/cookbook/form/data_transformers.html
Basically, you have told the form it is getting an array, and you've given it something else. The transformer is supposed to handle this.
If you need more help I'd need more information.
Also, somewhat bafflingly, you refer to 'myCollections' in your prose but don't show it, in your code.
^^^^^^^^^ fixed by edit.
Related
Hi I need a thinking help abaout form with entity class.
I have the edit function
/**
* #Route("/{id}/edit", name="admin_product_group_edit", methods={"GET","POST"})
*/
public function edit(Request $request, ProductGroup $productGroup): Response
{
$form = $this->createForm(ProductGroupType::class, $productGroup);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('admin_product_group_index', [
'id' => $productGroup->getId(),
]);
}
return $this->render('admin/product_group/edit.html.twig', [
'product_group' => $productGroup,
'form' => $form->createView(),
'scrollUp' => true,
]);
}
and I have the form Type
use App\Entity\ProductGroup;
use App\Entity\ProductType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ProductGroupType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('nameDe')
->add('nameEn')
->add('descriptionDe')
->add('descriptionEn')
->add('rank')
->add('active')
->add('creatDate')
->add('updateDate')
->add('productTypes', EntityType::class, [
// looks for choices from this entity
'class' => ProductType::class,
// uses the User.username property as the visible option string
'choice_label' => 'nameDe',
// used to render a select box, check boxes or radios
// 'multiple' => true,
// 'expanded' => true,
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => ProductGroup::class,
]);
}
}
by creating an new ProductGroup all is fin but by edit it, I cannot get the edit Form.
I get this error
Argument 1 passed to App\Controller\Admin\ProductGroupController::edit() must be an instance of App\Entity\ProductGroup, instance of App\Entity\ProductType given, called in /var/www/symfony-michael-roskosch/htdocs/vendor/symfony/http-kernel/HttpKernel.php on line 150
This is symfony 4.3 with symfony2 i had no problems with that, can you giv me a tip?
ok i found it
I had the wrong repositoryClass llinked by the orm annotation
/**
- * #ORM\Entity(repositoryClass="App\Repository\ProductTypeRepository")
+ * #ORM\Entity(repositoryClass="App\Repository\ProductGroupRepository")
*/
class ProductGroup
{
It was not a good idea to take the entity name ProductType because than you have the form ProductTypeType. After bin/console make:crud some mistakes was in the code. I don't know if I did them last night or it cames by the crud process it self.
nevermind now it works :-)
I've extended Symfony's EntityType as UserChooserType for use with my User entity and Select2. The choice list for the UserChooserType comes from an ldap query (via an ajax call), not a Doctrine query. So the field starts out blank.
The User entity is related to many different entities across my application. But if I want the UserChooserType to load with a current the selected User I have to add a listener to every form that uses it. e.g.:
class SiteType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$siteAdminOpts = array('label' => 'entity.site.admin', 'required'=>false);
//opts for the UserChooserType
$builder
->add('siteName', FT\TextType::class, array('label' => 'entity.site.name'))
->add('siteAdmin', UserChooserType::class, $siteAdminOpts )
//must be added to every form type that uses UserChooserType with mod for the datatype that $event->getData() returns
->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event){
$site = $event->getData();
$form = $event->getForm(); //SiteType
if($user = $site->getSiteAdmin()) $siteAdminOpts['choices'] = array($user);
$form->add('siteAdmin', UserChooserType::class, $siteAdminOpts);
});
}
//etc.
tldr;
I'd like to either:
set UserChooserType's choices option to the selected user in UserChooserType::configureOptions(), or
move ->addEventListener(...) into UserChooserType::buildForm().
Any idea how it might be done?
Here is the UserChooserType:
class UserChooserType extends AbstractType
{
/**
* #var UserManager
*/
protected $um;
/**
* UserChooserType constructor.
* #param UserManager $um
*/
public function __construct(UserManager $um){
$this->um = $um; //used to find and decorate User entities. It is not a Doctrine entity manager, but it uses one.
}
/**
* #inheritDoc
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$data = $event->getData();
if (!$data) return;
$user = $this->um->getUserByUserName($data);
if(!$user->getId()) $this->um->saveUser($user); //create User in db, if it's not there yet.
});
$builder->resetViewTransformers(); //so new choices aren't discarded
$builder->addModelTransformer(new CallbackTransformer(
function ($user) { //internal storage format to display format
return ($user instanceof User) ? $user->getUserName() : '';
},
function ($username) { //display format to storage format
return ($username) ? $this->um->getUserByUserName($username) : null;
}
));
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'class' => 'ACRDUserBundle:User',
'label' => 'ldap.user.name',
'choice_label' => function($user, $key, $index){
$this->um->decorateUser($user);
$label = $user->getDetail('displayName');
return $label ? $label : $user->getUserName();
},
'choice_value' => 'userName',
'choices' => [],
'attr' => array(
'class' => 'userchooser',
'placeholder' => 'form.placeholder.userchooser'
)
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'my_userchooser';
}
/**
* #inheritDoc
*/
public function getParent() {
return EntityType::class;
}
}
This helped me out:
https://symfony.com/doc/current/reference/forms/types/entity.html#using-choices
Here is how I used it (again with select 2):
public function buildForm(FormBuilderInterface $builder, array $options)
{
/** #var ProductCollection $productCollection */
$productCollection = $builder->getData();
$builder
->add('products', EntityType::class,
[
'class' => Product::class,
'required' => FALSE,
'expanded' => FALSE,
'multiple' => TRUE,
'choices' => $productCollection->getProducts(), // We only preload the selected products. The rest come from api.
'attr' => [
'data-toggle' => 'select',
'data-options' => json_encode([
'ajax' => [
'url' => '/admin/product/autocomplete',
'dataType' => 'json'
]
])
],
'choice_label' => function (Product $product) {
return $product->getName();
},
'choice_attr' => function (Product $product) {
return [
'data-avatarsrc' => $product->getImage()->getUrl(),
'data-caption' => $product->getSkus()->first()->getSku(),
];
},
]
)
;
}
And here is my JS for the init of the select2 (copy/paste):
function() {
var elements = document.querySelectorAll('[data-toggle="select"]');
function templateResult(element) {
let avatarsrc, caption;
if (element.id && element.avatarsrc) {
avatarsrc = element.avatarsrc
caption = element.caption ? ' ' + element.caption : ''
}
else if (element.element) {
avatarsrc = element.element.dataset.avatarsrc ? element.element.dataset.avatarsrc : ''
caption = element.element.dataset.caption ? ' ' + element.element.dataset.caption : ''
}
if (!avatarsrc) {
return element.text + caption
}
let wrapper = document.createElement("div");
return wrapper.innerHTML = '<span class="avatar avatar-xs mr-3 my-2"><img class="avatar-img rounded-circle" src="' + avatarsrc + '" alt="' + element.text + '"></span><span>' + element.text + '</span><span class="badge badge-soft-success ml-2">' + caption + '</span>', wrapper
}
jQuery().select2 && elements && [].forEach.call(elements, function(element) {
var select, additionalOptions, select2options;
additionalOptions = (select = element).dataset.options ? JSON.parse(select.dataset.options) : {};
select2options = {
containerCssClass: select.getAttribute("class"),
dropdownCssClass: "dropdown-menu show",
dropdownParent: select.closest(".modal") ? select.closest(".modal") : document.body,
templateResult: templateResult,
templateSelection: templateResult
}
$(select).select2({...select2options, ...additionalOptions})
})
}(),
Some remarks first:
The field name UserChooserType is a bit elaborated. UserType is shorter and just as clear, and fits the Symfony naming conventions better
I wouldn't extend UserChooserType from EntityType. Doc says EntityType is specifically dedicated to entities coming from Doctrine. It adds magic so that the field is easily configured around Doctrine: transformers, automatic fetching of choices from the DB, etc. If your users are fully defined in the LDAP, I would instead recommend extending ChoiceType and populate your choices from the LDAP directly.
Coming back to your problem, what you want here is to leverage the almighty power of dependency injection, by declaring your field type as a service. After having done that, instead of:
$builder->add('siteAdmin', UserChooserType::class, $siteAdminOpts)
You will do (assuming you chose the form name user_chooser_type):
$builder->add('siteAdmin', 'user_chooser_type', $siteAdminOpts)
You need to inject the security.token_storage service into your field type. This is the service that holds the current user's information, you can access it like this:
$user = $securityTokenStorage->getToken()->getUser();
With this the population of the default value can happen at the field type level instead of its parent.
Using this, you could also add the LDAP choices at field type level too, by injecting a service able to communicate with the LDAP.
It should finally noted that all default symfony field types are also declared as services.
EDIT:
Previous answer is beside the point.
In Symfony, I'm not aware of any possible simple way to modify the choice list of a choice/entity field after it has been created. I don't think there is, and actually I might have done the same as you to tackle the issue you're describing.
My opinion is that you're already doing what needs to be done in this case.
If you're really motivated though, I think it might just be possible to move the event listener in the form type like this:
->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) use ($options) {
if ($form->hasParent()) {
$data = $event->getData();
$form = $event->getForm();
$method = 'get' . ucfirst($form['action_name']);
if($user = $data->$method()) $siteAdminOpts['choices'] = array($user);
$form->getParent()->add($options['form_name'], UserChooserType::class, $siteAdminOpts);
}
});
Something like that. Not sure how that would work though.
I'm still interested in seeing if anyone comes up with a clean solution.
Relating to a cars application, I have a form where the user can choose brand and model ; the aim is that the model depends on the brand. For example, when you choose "Brand A", then only models related to brand A are displayed.
For now, I am already blocked on the initial form (where no data is set) ; there is a default brand displayed, and I would like models relative to this brand being displayed.
I followed some tutorials to add an event subscriber, but I can't make it works ; I am unable to get brand's field value into my subscriber... I tryed to get the Brand entity, but logically it is empty (because the form has not been submitted).
Anybody has an idea ?
FormType :
public function buildForm( FormBuilderInterface $builder, array $options ) {
$builder->add( 'brand', 'entity', array(
'class' => 'MyBundle:Brand',
'property' => 'name',
));
$builder->add( 'model', 'entity', array(
'class' => 'MyBundle:Model',
'property' => 'name',
));
/* Add event for the first model choices */
$builder->addEventSubscriber( new ModelChoicesSubscriber() );
}
FormSubscriber :
class ModelChoicesSubscriber implements EventSubscriberInterface {
public static function getSubscribedEvents() {
return array( FormEvents::PRE_SET_DATA => 'preSetData' );
}
public function preSetData( FormEvent $event ) {
$data = $event->getData();
$form = $event->getForm();
if( $data == null ) {
return;
}
$brand = $form->get( 'brand' );
}
}
I'm trying to set a selected value inside an entity field. In accordance with many discussions I've seen about this topic, I tried to set the data option but this doesn't select any of the values by default:
class EventType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('place', 'entity', array(
'class' => 'RoyalMovePhotoBundle:Place',
'property' => 'name',
'empty_value' => "Choisissez un club",
'mapped' => false,
'property_path' => false,
'data' => 2
))
->add('begin')
->add('end')
->add('title')
->add('description')
;
}
// ...
}
By looking for more I've found that some people had to deactivate the form mapping to the entity. That seems logical so I tried to add 'mapped' => false to the options, without success...
If it can help, here's my controller:
class EventController extends Controller
{
// ...
public function addAction()
{
$request = $this->getRequest();
$em = $this->getDoctrine()->getManager();
$event = new Event();
$form = $this->createForm(new EventType(), $event);
$formHandler = new EventHandler($form, $request, $em);
if($formHandler->process()) {
$this->get('session')->getFlashBag()->add('success', "L'évènement a bien été ajouté.");
return $this->redirect($this->generateUrl('photo_event_list'));
}
return $this->render('RoyalMovePhotoBundle:Event:add.html.twig', array(
'form' => $form->createView()
));
}
}
And the EventHandler class:
class EventHandler extends AbstractHandler
{
public function process()
{
$form = $this->form;
$request = $this->request;
if($request->isMethod('POST')) {
$form->bind($request);
if($form->isValid()) {
$this->onSuccess($form->getData());
return true;
}
}
return false;
}
public function onSuccess($entity)
{
$em = $this->em;
$em->persist($entity);
$em->flush();
}
}
I'm a bit stuck right now, is there anyone who got an idea?
You only need set the data of your field:
class EventController extends Controller
{
// ...
public function addAction()
{
$request = $this->getRequest();
$em = $this->getDoctrine()->getManager();
$event = new Event();
$form = $this->createForm(new EventType(), $event);
// -------------------------------------------
// Suppose you have a place entity..
$form->get('place')->setData($place);
// That's all..
// -------------------------------------------
$formHandler = new EventHandler($form, $request, $em);
if($formHandler->process()) {
$this->get('session')->getFlashBag()->add('success', "L'évènement a bien été ajouté.");
return $this->redirect($this->generateUrl('photo_event_list'));
}
return $this->render('RoyalMovePhotoBundle:Event:add.html.twig', array(
'form' => $form->createView()
));
}
}
In order to option appear selected in the form, you should set corresponding value to entity itself.
$place = $repository->find(2);
$entity->setPlace($place);
$form = $this->createForm(new SomeFormType(), $entity);
....
For non-mapped entity choice fields, the method I found easiest was using the choice_attr option with a callable. This will iterate over the collection of choices and allow you to add custom attributes based on your conditions and works with expanded, multiple, and custom attribute options.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('place', 'entity', array(
//...
'choice_attr' => function($place) {
$attr = [];
if ($place->getId() === 2) {
$attr['selected'] = 'selected';
//for expanded use $attr['checked'] = 'checked';
}
return $attr;
}
))
//...
;
}
When you use the query_builder option, and the data option expects an collection instance, and you don't want to touch your controller by adding setDatas for only certain fields, and you already have your querybuilder and the ids of the repopulating options in your form type class, you can repopulate a selection as following:
// Querybuilder instance with filtered selectable options
$entities = $qb_all;
// Querybuilder instance filtered by repopulating options (those that must be marked as selected)
$entities_selected = $qb_filtered;
Then in your add() Method
'data' => $entities_selected->getQuery()->getResult(), // Repopulation
'query_builder' => $entities,
EDIT: Real use case example
You want to repopulate a checkbox group rendered with following elements:
Label: What is your favourite meal?
4 Checkboxes: Pasta, Pizza, Spaghetti, Steak
And you want to repopulate 2 Checkboxes:
Pizza, Steak
$qb_all would be a QueryBuilder instance with the all 4 selectable Checkboxes
$qb_filtered would be a new additional QueryBuilder instance with the repopulating Checkboxes Pizza, Steak. So a "filtered" version of the previous one.
I have two models, Lesson and Evaluation. Each lesson can have multiple evaluations.
I am trying to set up an embedded form which will allow users to enter all of this data at the same time.
It works fine for adding and editing data, however I have a problem if I try to remove an evaluation.
For example, I have a lesson with three evaluations attached. I then submit with form again but with one of those removed.
In the controller, I first get the lesson being edited, then get its evaluations and loop through them, printing the ids. Three ids are printed as expected.
Next, I bind the request to the form and check if it is valid. I then get the evaluations again and loop through them once more to check that they've been removed, however all three ids were still there!
If I print the raw POST data, there are only two.
Can anyone see what I have done wrong?
Here is my controller code:
public function editAction($id = NULL)
{
$lesson = new Lesson;
if ( ! empty($id))
{
$lesson = $this->getDoctrine()
->getRepository('LessonBundle:Lesson')
->find($id);
}
foreach ($lesson->getEvaluations() as $evaluation)
{
print_r($evaluation->getId());
print_r('<br />');
}
$form = $this->createForm(new LessonType(), $lesson);
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
foreach ($lesson->getEvaluations() as $evaluation)
{
print_r($evaluation->getId());
print_r('<br />');
}
die();
$em = $this->getDoctrine()->getEntityManager();
$em->persist($lesson);
$em->flush();
}
}
}
Here is my lesson form:
class LessonType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('evaluations', 'collection', array(
'type' => new EvaluationType(),
'allow_add' => true,
'by_reference' => false,
'allow_delete' => true,
));
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'LessonBundle\Entity\Lesson',
);
}
public function getName()
{
return 'Lesson';
}
}
And finally, my Evaluation form:
class EvaluationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('report');
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'LessonBundle\Entity\Evaluation',
);
}
public function getName()
{
return 'Evaluation';
}
}
Any advice appreciated.
Thanks.
I think your form is not binded properly with the Class.
have a look at here http://symfony.com/doc/2.0/cookbook/form/form_collections.html
Form should look like this
$builder
->add('name lesson')
->add('evaluation', 'collection', array('type'=>new EvaluationsType()))
YOu need to create a new form class with other forms embedded.
The other way is to manually check the posted data and remove the evalauation manually in the controller and then persist the Lesson again
I got around in by using:
$lesson = $form->getData();