Symfony: embedding collection of forms - php

I'm trying to embed collection of forms into one based on this cookbook: http://symfony.com/doc/current/cookbook/form/form_collections.html
I have following database shcema: product ---< POS shortcut >--- POS item
in controller i'm initiatig form like this:
$pos = new PosList();
for ($i=0;$i<10 ;$i++ ) {
$scut1 = new PosShortcut();
$pos->addPosShortcut($scut1);
}
$form = $this->createForm(new PosListType(), $pos);
Then i have form for POSShortcut:
$builder
->add('posList','hidden')
->add('product','entity',array(
'required'=>false,
'empty_value'=>'Choose product...',
'label'=>'Shordcut product',
'class'=>'StockBundle:Product',
'property'=>'name'
));
And of course main form, what includes PosShortcut form:
<...>
->add('posShortcut','collection',array('type'=>new PosShortcutType()))
<...>
Now the problem is that for a POS shortcut item, POSList id is set to NULL when it's written in database. Reason is very simple, i haven't set PosList value for new shortcut when i'm creating them in controller at firstplace. But the issue is that i can not do that in this state, because POS item does not exists in database yet.
How to get over this problem ?

class PosList
{
public function addPosShortcut($shortcut)
{
$this->shortcuts->add($shortcut);
$shortcut->setPosList($this); // *** This will link the objects ***
}
Doctrine 2 will take care of the rest. You should be aware that all 10 of your shortcuts will always be posted.

Related

Modify admin configuration values on save

I have created a configuration form in Grav's admin panel, and I want to extend/modify some of it's values on save.
More precisely, I have a list form element that looks like this in the blueprint:
topics:
type: list
fields:
.name:
type: text
.unique_id:
type: text
readonly: true
default: generate_on_save
On save, I want to replace all generate_on_save values with a unique id.
I tried to hook into the onAdminSave Event, but the Event Object contained just an instance of \Grav\Common\Data\Blueprint and no actual form data. I then tried to modify the request object, but when I register the modified request in the grav container, I get an error Cannot override frozen service 'request'.
How can I accomplish this task?
I did the following which works fine:
In config file /user/themes/quark/blueprints.yaml, I copied your field definition.
In Admin I added some topics on the config page of theme Quark.
The 'Save' action was captured by the following eventhandler:
public function onAdminSave(Event $event) {
/** #var Data */
$form = $event['object'];
$topics = $form['topics'];
foreach ($topics as &$topic) {
if ($topic['unique_id'] === 'generate_on_save') {
$topic['unique_id'] = str_rot13($topic['name']);
}
}
// Note: Updated $form['topics'] must be re-assigned
$form['topics'] = $topics;
}
The topics with there "unique" values have correctly been written to /user/config/themes/quark.yaml

"Unable to reverse value for property path" for Symfony2 form ChoiceType field on Select2

Long story short, in Symfony 2.8 I've got Movie entity with actors field, which is ArrayCollection of entity Actor (ManyToMany) and I wanted the field to be ajax-loaded Select2.
When I don't use Ajax, the form is:
->add('actors', EntityType::class, array(
'class' => Actor::class,
'label' => "Actors of the work",
'multiple' => true,
'attr' => array(
'class' => "select2-select",
),
))
And it works.
I tried to put there an empty Select field:
->add('actors', ChoiceType::class, array(
'mapped' => false,
'multiple' => true,
'attr'=>array(
'class' => "select2-ajax",
'data-entity'=>"actor"
)
))
The Select2 Ajax works, everything in DOM looks the same as in previous example, but on form submit I get errors in the profiler: This value is not valid.:
Symfony\Component\Validator\ConstraintViolation
Object(Symfony\Component\Form\Form).children[actors] = [0 => 20, 1 => 21]
Caused by:
Symfony\Component\Form\Exception\TransformationFailedException
Unable to reverse value for property path "actors": Could not find all matching choices for the given values
Caused by:
Symfony\Component\Form\Exception\TransformationFailedException
Could not find all matching choices for the given values
The funny part is the data received is the same as they were when it was an EntityType: [0 => 20, 1 => 21]
I marked field as not mapped, I even changed field name to other than Movie entity's field name. I tried adding empty choices, I tried to leave it as EntityType but with custom query_builder, returning empty collection. Now I'm out of ideas.
How should I do it?
EDIT after Raymond's answer:
I added DataTransformer:
use Doctrine\Common\Persistence\ObjectManager;
use CompanyName\Common\CommonBundle\Entity\Actor;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
class ActorToNumberTransformer implements DataTransformerInterface
{
private $manager;
public function __construct(ObjectManager $objectManager)
{
$this->manager = $objectManager;
}
public function transform($actors)
{
if(null === $actors)
return array();
$actorIds = array();
foreach($actors as $actor)
$actorIds[] = $actor->getId();
return $actorIds;
}
public function reverseTransform($actorIds)
{
if($actorIds === null)
return array();
foreach($actorIds as $actorId)
{
$actor = $this->manager->getRepository('CommonBundle:Actor')->find($actorId);
if(null === $actor)
throw new TransformationFailedException(sprintf('An actor with id "%s" does not exist!', $actorId));
$actors[] = $actor;
}
return $actors;
}
}
Added it at the end of the MovieType buildForm():
$builder->get('actors')
->addModelTransformer(new ActorToNumberTransformer($this->manager));
$builder->get('actors')
->addViewTransformer(new ActorToNumberTransformer($this->manager));
And added service:
common.form.type.work:
class: CompanyName\Common\CommonBundle\Form\Type\MovieType
arguments: ["#doctrine.orm.entity_manager"]
tags:
- { name: form.type }
Nothing changed. On form submit, reverseTransform() gets the proper data, but profiler shows the same error. That's a big mistery for me now...
You'll need to add a DTO (Data Transformer ) to transform the value received from your form and return the appropriate object .
Since you're calling the value from Ajax it doesn't recognized it anymore as a an object but a text value.
Examples :
Symfony2 -Use of DTO
Form with jQuery autocomplete
The correct way isn't Data Transformer but Form Events, look here:
http://symfony.com/doc/current/form/dynamic_form_modification.html#form-events-submitted-data
In the example you have the field sport (an entity, like your Movie) and the field position (another entity, like actors).
The trick is to use ajax in order to reload entirely the form and use
PRE_SET_DATA and POST_SUBMIT.
I'm using Symfony 3.x but I think it's the same with 2.8.x
When you add data transformers and nothing seems to change, it sounds like the data never goes through your data transformers. The transformation probably fails before your new data transformers are called. Try to add a few lines to your code:
$builder->get('actors')->resetViewTransformers();
$builder->get('actors')->resetModelTransformers();
// and then add your own

Create gravity form poll based on post types

Is there a way to create/update form poll fields based on a content type? For example, I've got a post type called Candidate and I'd like like to dynamically update a poll list when a new Candidate is added, or when one is removed.
The reason I'm looking for this is because I'm creating a voting mechanism for this client and they have requested that users see an image, the name, and brief Bio of who they are voting for. My idea is to tie in the names so that I can target a hidden Gravity Form poll on page so when the voter clicks, it updates the corresponding named checkbox.
I can of course add each Candidate one by one, and then add each candidate one by one in the form, but was hoping there was a way to do that in code. So far I haven't found much other than filters in the Gravity Forms Documentation.
To reiterate, my question here is not the frontend connection, rather how to dynamically update/add an option in a poll field in a form when content is created for a Candidate post type.
Any help would be appreciated.
I believe the solution you're after is documented here:
http://www.gravityhelp.com/documentation/gravity-forms/extending-gravity-forms/hooks/filters/gform_pre_render/
Probably a combination of solution examples #1 and #2 on that page will fit your needs? So -
Create a category of standard Wordpress pages (category name: "Candidates"), and the pages would contain the candidate information (bio, photo, etc).
In your functions.php file for your current theme, you'd add something like the following to pull out that category's worth of posts:
// modify form output for the public page
add_filter("gform_pre_render", "populate_checkbox");
// modify form in admin
add_filter("gform_admin_pre_render", "populate_checkbox");
function populate_dropdown($form) {
// some kind of logic / code to limit what form you're editing
if ($form["id"] != 1) { return $form; }
//Reading posts for "Business" category;
$posts = get_posts("category=" . get_cat_ID("Candidates"));
foreach ($form['fields'] as &$field) {
// assuming field #1, if this is a voting form that uses checkboxes
$target_field = 1;
if ($field['id'] != $target_field) { break; }
// init the counting var for how many checkboxes we'll be outputting
// there's some kind of error with checkboxes and multiples of 10?
$input_id = 1;
foreach ($posts as $post) {
//skipping index that are multiples of 10 (multiples of 10 create problems as the input IDs)
if($input_id % 10 == 0) { $input_id++; }
// here's where you format your field inputs as you need
$choices[] = array('text' => $post->post_title, 'value' => $post->post_title);
$inputs[] = array("label" => $post->post_title, "id" => "{$field_id}.{$input_id}");
// increment the number of checkboxes for ID handling
$input_id++;
}
$field['choices'] = $choices;
$field['inputs'] = $inputs;
}
// return the updated form
return $form;
}

joomla 3.x tags in custom component fails

Running Joomla 3.3.0-dev
I'm following the info posted here about adding tag support to a third-party component.
I've added the content type to the #__content_types table and modified my table file like this:
class MycomponentTableElement extends JTable
{
public $tagsHelper = null; // failed when protected and public
public function __construct(&$_db)
{
parent::__construct('#__mycomponent', 'id', $_db);
// Add Joomla tags
JObserverMapper::addObserverClassToClass('JTableObserverTags', 'MycomponentTableElement', array('typeAlias' => 'com_mycomponent.element'));
//$this->_observers = new JObserverUpdater($this); JObserverMapper::attachAllObservers($this); // failed with or without this line
}
I added the tag field in the edit template, and it worked fine-- but when I save an object I get the following error:
Save failed with the following error: Unknown column 'tagsHelper' in 'field list'
What am I missing? There's no other steps (besides front-end steps!) that are mentioned. It seems like I need to modify the model but that info is not applicable.
Thanks
"This Page Needs Copy Editing" and it's really true!
I also follow initial steps as described in page
Register a 'Content type' for the extension view(s)
Add 'Observer methods' to the extension table class(es)
Add 'Tag fields' to the extension edit forms
But to make field tag works on custom extensions I need to explicit set form field value in view file of backend:
$tagsHelper = new JHelperTags;
$this->form= $this->get('Form');
$this->form->setValue('tags', null, $tagsHelper->getTagIds( $this->item->id, 'com_custom.viewname') );
in this way on edit page all seems to work correctly.. surely exist better and more clean method, but until doc page will not be updated, this can help someone!
1- Add tag field to your xml form file or edit template file
2- Modify #__content_types table file:
function __construct(&$db)
{
parent::__construct('#__ir_products', 'id', $db);
JTableObserverTags::createObserver($this, array('typeAlias' => 'com_itemreview.product'));
}
3- Modify model file getItem function:
public function getItem($pk = null)
{
$item = parent::getItem($pk);
if (!empty($item->id))
{
$item->tags = new JHelperTags;
$item->tags->getTagIds($item->id, 'com_yourcomponent.yourmodel');
}
return $item;
}

Symfony2 Saving data of related Entity after submiting form

I'm starting developing with Symfony2 and looks like I need help. I have Product entity related with SynchronizationSetting entity. I can edit product data by form maped with his entity. But I also need to modify some data related to product in SynchronizationSetting. To do that I've modified the form so it look like that (Vendor\ProductBundle\Form\ProductType.php):
...
->add('synchronization_setting', 'choice', array(
'choices' => array('daily' => 'Daily', 'weekly' => 'Weekly', 'never' => 'Never'))
After form is submitted selected checkbox values are passed to setSynchronizationSetting method in Product Entity. Then I do that (Vendor\ProductBundle\Entity\SynchronizationSetting.php):
public function setSynchronizationSetting($data)
{
$synchronizationSetting = new SynchronizationSetting();
$synchronizationSetting->setDaily(in_array('daily', $data) ? '1' : '0');
...
}
And now I need to somehow save those SynchronizationSetting entity into database. I read that calling entity manager from here is very bad practice so... how should I save this?
One possible way (I'm not sure if it's good practice)
public function setSynchronizationSetting($data)
{
$synchronizationSetting = new SynchronizationSetting();
$synchronizationSetting->setDaily(in_array('daily', $data) ? '1' : '0');
}
public function retSynchronizationSetting()
{
return $this->synchronizationSetting;
}
Then in your controller in place where you handle form data you call retSynchronizationSetting() and save entity using EntityManager.

Categories