cakePHP: automagic form elements, populating selection list - forms

I have two tables, users{name,id,age_range_id} and age_ranges{id,range_name}.
There are also two models, controllers and the proper view files.
In the views I have the adduser.ctp file, which hold the proper form.
What I want is to have an input (select) that will hold the options from age_ranges.name field.
So, in the users model I've added var $hasMany = 'age_ranges';
What's next?
I know that I can use the $this->set to store the options as an array in the controller and then use it in the view.
but I assume(wrongly?) that by relating the models there is an 'automatic' way to do it.
Which lead me to the question: how?

I won't repeat what Thorpe and dogmatic have already written. They are both correct.
However, although it's difficult to be sure without seeing your model files, commonsense tells me that in the User model the relationship should be User:hasOne:AgeRange and in the AgeRange model it is AgeRange:hasMany:User, not the other way round as you have written.
Also, you do not specify the table name ('age_ranges') in the relationship, but the Model name ('AgeRange').
See these pages in the manual:
http://book.cakephp.org/view/1001/Understanding-Models & http://book.cakephp.org/view/1039/Associations-Linking-Models-Together

add $this->set('ageRanges', $this->User->AgeRange->find('list')); to the controller action
then add $this->Form->input('age_range_id') to the form

You can do this:
$this->User->AgeRange->find('list') and pass that to the view for a select statement

Related

Lightswitch HTML Client, Set Default Value of List Picker

Lightswitch renders my navigation property as a list picker, but I can't figure out how to set a default value on it. There must be a simple way to do it. I've scoured the net, and all the suggestions look hopelessly kludgy. Is there a good comprehensive tutorial out there for Lightswitch? The most common tasks like setting the default value on a dropdown are ridiculously hard to figure out.
Here's how I did it.
myapp.Address.created = function (entity) {
myapp.activeDataWorkspace.MailListData.CountryRegion_LUs.filter("CountryRegionCode eq 'US'").execute().then(function (result) {
entity.CountryRegion_LU = result.results[0];
});
}
You want to write a handler for the created Javascript event for the parent entity. I'm binding CountryRegion_LUs, which are in the Address entity, so I am binding to the created event of the Address entity, not the CountryRegion_LUs entity. "MailListData" is the name of my database. I'm using an OData query to pull out the CountryRegion_LU that has a CountryRegionCode of "US." I could have simply used "load()" instead of .filter("CountryRegionCode eq 'US'").execute() to load all the records, and then picked the member of the result-set I wanted, say results.result[221], but then I'd be bringing all the data over and filtering client-side.
refer to this post of which I asked myself, there is a detailed answer on the problem you have above: it explains how to set your modal picker/details picker with a default value
Lightswitch HTML Client - set modal picker value when screen created
any questions feel free to ask

Symfony2: Entity instantiation upon Form-Submit depending on user selection

I'm working with Symfony2 to set up a form, where a Shelf-Entity can be edited.
A shelf contains a collection of Readable-Entities (e.g. Book, Magazine, etc. - all inherit from Readable).
The user has the possibility to add more Readable-Entities (the form is extended via JavaScript) and from a dropdown he can select the type of Readable he wants to add. Depending on the selected dropdown-value, different form fields are rendered. So far so good.
Now, when the form is submitted to the server, depending on the Readable-Type the user selected in the form, a different entity-type should be instantiated.
If I don't do anything, Symfony just instantiates the base class Readable (and not Book, Magazine, etc.).
How can I tell Symfony to instantiate the correct type of Readable depending on the selected value from the dropdown?
I tried with FormEvent-Listeners, but:
in PRE_SUBMIT I only get an array containing the "raw" form data with $event->getData(), i.e. no entities have been instatiated so far. However, at this stage, I still have access to value of the dropdown.
in SUBMIT the form data was already assigned to the appropriate entities. Also the new Readable was already instatiated with the base Readable-Class. But now, I cannot access anymore the value from the dropdown.
What is the correct way to do this?
EDIT
Added a minimal Code-Example for the Shelf FormType:
https://gist.github.com/anonymous/401495b701982adafb96
Code for infinite_form_polycollection:
https://gist.github.com/anonymous/b5f0ed10ca9c52177f01
Have you tried looking at this part of the doc? As "embedding a form" seems to fit your needs.
It seems that there was something wrong with the PHP-Files of the PolyCollection in the vendor-directory, because after removing everything related to the Infinite Form Bundle from the vendor-dir and reinstalling it with composer, everything is working now. But thanks for your efforts YoannCh

Zend Form changing element type in controller

I have my Zend_Form, and sometimes, one of the fields should be hidden, and not seen by the user. Is there a way when I call the form in my controller, I could change one of the fields to be hidden?
Thanks
Kousha
You can remove the element using:
$form->removeElement('my-element-name');
in the controller.
You could also create two forms, one overriding the other, in which the child calls $this->remove('my-element-name').
Or, you could make the form constructor accept a boolean $flag that determines whether to add the field to the form.
So, as you can see, lots of different ways to structure it.
To change that field to one of type "hidden" (i.e. <input type="hidden">) is a different thing, but I'm not sure that's what you mean/need/want.
The best solution I have for this is to add a specific class to the element when it needs to be hidden. It may not be the perfect solution, but let me explain.
First, its very difficult to switch from one element type to another in Zend Form. Your elements are actually classes. So the text is Zend_Form_Element_Text - so its not just as easy as changing the 'type' attribute.
If the element must remain on the form (so, not removing it like the answer above suggests), your only other option would be hiding it with CSS.
Try the following code when it needs to be hidden:
$element = $form->getElement('MyElement');
$newClass = trim($element->getAttrib('class') . ' hidden');
$element->setAttrib('class', $newClass);
Then, of course, create CSS for the .hidden class.
Hope this helps!

ASP.NET MVC 2 - Control Advice

I'm new to ASP.NET MVC 2, and I need some advice on the best 'Control' to use for this situation. (I'm know ASP.NET MVC doesn't really use server controls, but there are a number of add-ons such as MVC Controls ToolKit).
Here's what I need to do. I have a table in a database which contains a list of tests. I need to be able to display these in a View, and allow the user to select them in some way (via checkboxes or whatever).
Then I need to be able to determine which items are selected.
Can someone tell me the best way to achieve this?
Any help/comments are appreciated.
TIA.
If you do it with client side functionality, it will end up consisting mainly of two parts:
The visual HTML
The functional Javascript
How would I'd do it
I'd create a partial view that displays the table. If you need to reuse this, put the partial in Views/Shared folder
Each TR of the table would have serialized JSON of the object that is displayed in that particular row. Serialization can be done by writing a custom object extension method, so you can call ToJson() on any object afterwards
<tr data='<%= this.Model[0].ToJson()'>
<td class="actions"> Select ... </td>
<td>...</td>
...
</tr>
Mind the extra column with actions that you need to provide.
also add a Javascript that would provide the client side functionality (important: this script uses jQuery)
$(function(){
var selection = {};
$(".actions a.action-select").click(function(evt){
evt.preventDefault();
var context = $(this);
var rowObj = $.parseJSON(context.closest("tr[data]").toggleClass("selected").attr("data"));
if (selection[rowObj.Id])
{
// deselect
delete selection[rowObj.Id];
}
else
{
// select
selection[rowObj.Id] = rowObj;
}
});
This way your rows will have additional selected class when they're selected and your selection object will always have selected rows (or better said their objects) taht you can use however you please.
Additional note
Why did I set selection to be an object rather than an array? Because Javascript objects are kind of associative arrays so searching for a particular element is faster than enumerating over its elements it it was a normal array. This way I can immediately see whether row is selected or not and also remove an element from it directly.
Outcome
This way you'll have a reusable table that you can put on various pages (hence similarities with user controls). but in case you'd need to add several of these tables to your pages you'd have to tweak them a little so that client-side functionality won't mix data between different tables.

symfony form - delete embedded form object

I have a two Symfony forms:
ShoppingListForm
ShoppingListItemForm
I'm embedding the ShoppingListItemForm inside the ShoppingListForm many times. i.e. A shopping list contains many items.
So the ShoppingListItemForm consists of two widgets:
item_id (checkbox)
shopping_list_id (hidden - foreign key)
What I would like to do is delete the corresponding ShoppingListItem object if the object exists and the checkbox is left unchecked.
I'm not sure how this delete would occur? Would I use a post validator to see which fields have/haven't been checked? I'm a bit lost on this one.
I'd do this by over-riding the ShoppingListForm's updateObject method and putting your custom delete() etc calls in there (be sure to call parent::updateObject() within it).
Depending how you implement it, you may also need to remove the embedded forms and their values to ensure saving still works correctly for the remaining objects. Try without, but if you do, you need to clear the following:
unset($taintedValues['ShoppingListItem'][$key]);
unset($this->embeddedForms['ShoppingListItem'][$key]);
unset($this->validatorSchema['ShoppingListItem'][$key]);
unset($taintedFiles['ShoppingListItem'][$key]);
If you want to see a custom updateObject method to get an idea how to interact with values etc:
http://www.symfony-project.org/forms/1_2/en/11-Doctrine-Integration#chapter_11_sub_customizing_the_updateobject_method
personnally, I would loop through the existing list items to see whether the corresponding checkboxes are checked in the action, and call the delete() method on the items for which it is not the case. I don't think it is the purpose of a post validator, I would do this directly in the action.