Symfony2: string values from choice fields not bound to form object - php

My app contains a form with three choice fields / dropdown lists.
The first is linked to a "relational" field in the entity, and works fine.
The user is supposed to choose a table link first.
The second and third are both linked to string fields in that same entity.
Through jQuery, these choice fields get populated with values based on the decision the user makes in the first dropdown list.
After submitting the form, there is an error for the second and third field: they contain invalid input. When I check the form object, their values were not bound; their values never arrived.
The choice fields for collecting string data from the user looks like this:
->add('sourceName', 'choice', array
(
'label' => 'Choose source name:',
'empty_value' => 'Please choose a table link first...',
'choices' => array(),
'attr' => array('class' => 'extFieldChoice'),
)
After jQuery has done its job, the html select element looks like this:
<select id="someId" name="someName[sourceName]" required="required"
class="extFieldChoice">
<option value="first">first</option>
<option value="second">second</option>
<option value="manymore">Many more...</option>
</select>
I suspect that the error can be found in the initially empty choices array. However, it would be impossible to fill it with all possible choices, because they run in the hundreds.

I've the same problem few days ago and it drive me nuts to find a solution, I get to this question and even probably it's too late I want to share the solutions I've found in case there'll be someone with the same problem, I have found three of them, but none of them seems to be the perfect solution.
In my case I have to save the city selected by an user based on the zipCode. When a user save a new address he wrotes the zipCode and then via ajax I fill-in the city select with options of the cities.
My "choice" field declaration:
$builder->add('city', 'choice', array(
'label' => 'form.city',
'read_only' => true,
'mapped' => false,
'required' => false,
'empty_value' => false,
'choices' => array('none' => 'form.empty.city'),
'data' => null
));
The problem is that the form validation look for two things:
If the form it's related with an entity looks forward the entity
to validate, you can skip this validation easily with the "mapped"
=> false parameter.
The form validation itself, if you have a "choice" type field with or without choices defined when the form validate look towards the first choices you have declared. And I haven't been able to skip the validation for only this field.
So the three ways I have found:
Use the form event and before whe bind the request to the form $builder->addEventListener(FormEvents::PRE_BIND, function (DataEvent $event) use ($xxx) { ...}); (I have an example of use at the linked article) we make the same query to the database we have made on the ajax, we retrieve the values and add them to the chocie field. This is the better way if we think in code, but we have to do the same query twice, and I don't want to do that.
In my case I have to store a string with the city name so another option is to add the city field as a hidden one and insert the whole select as an element. But I don't like this one for many reasons, two of them: I don't like the idea of insert a hole , with and between the other form fields created by symfony2; the other one is that it requires more jquery that it's necessary from my point of view.
Based on the second option, I was filling in some other hidden fields based on the city selection the user has made, so I only include one more hidden field to save the city name; and when the form is submited I remove all the options from the select, so it matches the choices I have defined.
$('#cityChoice').on({
change: function(){
var optionSelected = $(this).find('option:selected');
$('#city').val(optionSelected.val());
$('#latitude').val(optionSelected.data('lat'));
$('#longitude').val(optionSelected.data('lng'));
}
});
$('#myForm').on({
submit: function(){
$('#mySelect option').remove();
}
});
I've decided for the third option, but I think the three of them have bad sides.

Related

Increment index on multidimensional array using AJAX in cakePHP

first sorry if my question isn't clear at all.
So, I have an app with Transaction module in cakePHP. That module (at least) have 3 chained dropdowns like this Supplier > Products > Packages. User choose Supplier, then in products select box show the result only products from that selected supplier. So do the packages, options will show when choose products.
Simply, I use this reference to do first chain. It works. But when going into Packages, it isn't easy as first lol. Why? Because the second form where Products and Packages element have more complex dimensional array from first. In first form (Supplier element), I fetch its data with $this->request->data['Order]['supplier_id']
But in second form, the data that will passed from Ajax like $this->request->data['OrderDetail'][$index]['product_id'] where the index in second form have increment number.
Example:
<select id="Product0" name=data[OrderDetail][0][product_id]></select>
<select id="Product1" name=data[OrderDetail][1][product_id]></select>
<select id="Product2" name=data[OrderDetail][2][product_id]></select>
Then in my controller,
public function functionName() {
$product_id['index'] = $this->request->data['OrderDetail']['index']['product_id'];
}
EDITED
Sorry, forgot to post my ajax code.
<?php
$this->Js->get('#OrderSupplierId')->event('change',
$this->Js->request(array(
'controller'=>'products',
'action'=>'gpbs'),
array(
'update'=>'.OrderDetailProduct',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(
array(
'isForm' => true,
'inline' => true)
)
)
));
How can I pass the dynamic index too in AJAX??
So, when it sent to controller, data from every "form element" will match.
Thanks, and sorry for my bad language (and description)

cakephp drop-down lists using displayed value

Apologies for troubling everyone with the billionth or so question about CakePHP and drop-down lists.
I have a database of employees, with fields such as name, department etc.
What I want to achieve is that the standard view of all employees can be filtered by selecting available departments and submitting a form. The departments available to select in the filter are automatically populated from the existing departments already in the database.
I'm fairly new to CakePHP, but what I'm trying to achieve is a drop-down list that is a 1 x N extract from the database. In HTML this would look like:
<option value="Human Resources">Human Resources</option>
<option value="Finance">Finance</option>
The idea is then to take this input and use it for a SQL query along the lines of:
SELECT * from Employees WHERE Department = 'finance'
etc.
At the moment this is the code I'm using in the controller to generate a list of all existing departments:
$this->set('department', $this->Employee->find('list', array('fields' => 'Employee.Department')));
and this I'm using this in the view to then make that into a dropdown box:
echo $this->Form->input('faculty', array('label' => 'Faculty', 'empty' => array('Any'), 'options' => $department));
The problem I am encountering is that it generates HTML along the lines of
<option value="1">Human Resources</option>
<option value="2">Finance</option>
I have read and re-read the documentation on forms and the find functions, but I can't seem to find the answer.
The only way forward I've found from that would be to manually specify the options using array('value' => 'label'), which given how long the full form is (and the 50+ departments we're talking about), is not something I fancy doing!
Am I:
Missing the right option in the Form Helper or the find function?
Just plain doing it wrong?
I know the logic for the filtering function works fine because the checkboxes are ok, and I've played around with options in the URL and if I enter it manually everything is fine.
So, what I do to get an array that looks like what you want is:
$options = array_combine($department, $department);
echo $this->Form->input('faculty', array('label' => 'Faculty', 'empty' => array('Any'), 'options' => $options));
That should render something like:
<option value="Human Resources">Human Resources</option>
<option value="Finance">Finance</option>

L4: populate multiple text inputs

I'm working on an Laravel 4 project and we have an view with an dynamic form.
Form::text('title')
<ul>
<li>Form::text('movie_actor[]')</li>
<li>Form::text('movie_actor[]')</li>
<li>Form::text('movie_actor[]')</li>
...
</ul>
I've read that you need to set the validation for the multi fields to array. So I added the validation rules like so:
$v = Validator::make(Input::all(), array('title' => 'required', 'movie_actor' => 'array'));
When I enter some actors, leave the title empty and submit the form, then the user is redirected to the same page with:
return Redirect::route('movies.create')->withInput();
The problem is that I get the error htmlentities() expects parameter 1 to be string, array given.
The population works when I remove the actor inputs from the view or change the actor text fields to selects fields. But that is not what I want.
How can I populate the multi-text fields?
I had same issue too. I haven't figure out exactly why its happen but looks like those text input name should be "string" not array which means, you should do like follow:
<li>Form::text('movie_actor[0]')</li>
<li>Form::text('movie_actor[1]')</li>
<li>Form::text('movie_actor[2]')</li>
The differences are you need to manually add an index to those name array.

CakePHP does not auto-populate a field (that has no Model) after submission

The situation
I'm working on a large form which have been split into several tabs, both to group fields of a kind and make filling easier. The tabs are activated using JavaScript (jQuery) and the form is submitted whole (all tabs at once, even if there are blank fields).
I am trying to submit a hidden field along with the form to keep user's current tab. This way, when the form is submitted, data is saved and the user goes back to the very same tab it was before. This field is not attached to any Model, as it is just a helper.
The problem + what have I tried
The field is correctly populated by jquery as the user switch tabs, and it is submitted along with the form. This is what I did:
<?php
echo $this->Form->create('Briefing', array('enctype' => 'multipart/form-data'));
// This is my aux field, which is populated via jQuery as user switch tabs
echo $this->Form->hidden('tab-active', array('name' => 'tab-active', 'id' => 'tab-active'));
echo $this->Form->input('title');
echo $this->Form->submit('Save', array('class' => 'btn btn-success'));
echo $this->Form->end();
?>
Let's suppose the user submitted the form when it was at "Tab #4". When I debug($this->data); at my BriefingsController, this is what I get:
/app/Controller/BriefingsController.php (line 133)
array(
'tab-active' => 'tab-4',
'Briefing' => array(
'title' => 'My test title'
)
)
So my Controller receives the form data for both tab-active and Briefing.title fields, but when the form is loaded after submission, only the Model field is populated with the submitted data, and tab-active comes with an empty value. CakePHP does not auto populate the value for my non-model-attached field.
Any thoughts on that? Is this a default CakePHP behavior or is there something I could do to make it work(auto populate)? I have no problem with the jQuery (already tested it in several ways), the real problem is into getting this field populated back after form submission. Any help is much appreciated.
CakePHP populates forms with the data of the form's model. So if you create a form for 'Briefing' creation, CakePHP will look at the $this->data['Briefing'] array, and populate inputs matching the fields that are present in this array. So as your hidden 'tab-active' field is present inside the 'Briefing' Form creation, CakePHP expects your 'Briefing' model to have a 'tab-active' attribute.
So my guess is that your $this->data array should be :
array(
'Briefing' => array(
'tab-active' => 'tab-4',
'title' => 'My test title'
)
)

X-cart Form Administration: How to integrate a new Form Field Type

What I am essentially trying to do is to be able to utilize more Field Types than the very simple 'Text', 'Checkbox' or 'Select' when customizing a form in X-Cart.
Namely, I have custom fields in my User Profile form page (X-cart Admin > Settings > General Settings > User Profiles). The 'Field Type' I'm referring to is visible in this screenshot:
http://screencast.com/t/OA7b1UBUVN
The type of field I want to add is not simple; it is an complex form of a multi-select dropdown.
But for the purposes of this questions let's keep it simple: What would be the better way to add, for example, a choice for Radio Buttons?
Let me know if you need more clarifications.
Thanks!
Mat
So far, with manual wayfinding into X-Cart's architecture I've been able to figure out the following:
List of field types is defined in:
admin/user_profiles.php
// Field types
$types = array(
'T' => 'Text',
'C' => 'Checkbox',
'S' => "Select box",
The form for defining user profiles is built in:
skin/common_files/admin/main/user_profiles.tpl
The template file that interprets the selected field type is:
skin/common_files/main/register_additional_info.tpl
{if $v.type eq 'T'}
<input type="text"
[...]
In the database, custom fields information is stored in xcart_register_fields, and the values for those custom fields are in xcart_register_fields_values.
The database is read and written from:
include/register.php
Written:
if (!empty($additional_values)) {
foreach ($additional_values as $k => $v) {
func_array2insert(
'register_field_values',
array( [...]
Read:
[Not sure yet]

Categories