Increment index on multidimensional array using AJAX in cakePHP - php

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)

Related

How to add custom field in the content type of Drupal 7

I want to add a custom field which value will come from external API. As example values may be:
array(
'v1'=>'value1'
'v2'=>'value2'
'v3'=>'value3'
)
So, I want to display them in a dropdown menu as field in the content-type article.
I don't it is right answer, but as per my view it is not better to store all values of third party DB.
To achive your goal I will do like this.
Content type Article which include another two fields:
Number field: Id (api_db_id) : v1, v2, v3....
Text Field: Value (api_db_value) E.g: value 1, value 2 ...
These above field will be hidden.
Before render form E.g: by using hook_form_alter we can connect to third party API and get values and populate in select list
E.g:
function myhook_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'article'){
/*
Third Party API connection code which will generate $dropdown_array.
*/
$options = $dropdown_array;
// Alter form
$form['title'] = array(
'#type' => 'select',
'#default_value' => '1',// set default value.
'#options' => $options,
);
}//endif
}
And Final step will before submit form we will assign selected ID and value to our new field .
You should create a custom module to implement your field.
A good tutorial can be found HERE.
You can check out version 7 of the examples module, specifically the field_example which has very good documentation in the code.
Once you get your head around how it (the hooks) works, there really isn't all that much code to write.
Doing it this way is probably much better than trying to alter other types of fields, and it should automatically integrate with views as expected.

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>

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

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.

How to Update two text fields onchange of a dropdown list

Im building a web app using the yii framework. I have a dropdownlist and im calling an action and updating a div tag using ajax array 'update'=>'#price' field. the code works fine and it updates the price div.
But i want to update two fields like that, i tried passing an array to the update field. but it didnt work.
Any Idea how I can update two div tags and show two values using one action call?
Heres My Code..
echo CHtml::beginForm();
echo CHtml::dropDownList('amount_'.$position,'', array(1=>1,2=>2,3=>3),
array(
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('shoppingCart/updateAmount'),
'update'=>'#price_'.$position, //selector to update
)));
echo CHtml::endForm();
and in my action im just echoing
echo 'LKR '.Shop::priceFormat(#$product->getPrice($cart[$position]['Variations'], $value));
It'll be great if someone could help.
It's simply jQuery selector. I believe you can use comma for few ids. Or you can use class selector. (I think class selector would be better here)
'ajax' => array(
/* ... */
'update' => '#price_1, #price_2, #price_3',
/* or */
'update' => '.price'
)

CakePHP form selection as parameter

I have the following code in my index.ctp view to create a form:
<?php
echo $this->Form->create(false,array('url' => array('controller' => 'admins', 'action' => 'edit_gallery')));
echo $this->Form->input('name', array('options' => $array,'empty' => 'Select a gallery'));
echo $this->Form->end(__('Submit', true));
?>
Thi codes creates a dropdown list of items, each one with an associated number as value.
In my admins_controller I have the edit_gallery action implemented exactly as it comes when you bake a project, only that I changed the typical edit to edit_gallery.
What I want is the following: the user selects one item from the list, then clicks 'Submit', and he's taken to the edit_gallery.ctp view, with a form to edit the information of that item in the database and update it. My problem is that, instead of doing this, what happens is that when the user clicks Submit, a new item is created in the database, and it doesn't even show the ctp view.
In general, my question would be: how can I get the selected option of the form in the landing page after the user clicks 'Submit'?
Edit
Ideally, what I would want is that, when the user clicks 'Submit', it would send a request like admins/edit_gallery/x where x would be the value associated to the selection made by the user, without sending any other data to the action. I don't know if that's possible.
Thank you!
The edit method that CakePHP bakes check by default if data is not null, in other words, if a form has been submitted, and then updates that record.
So, when you redirect to *edit_gallery* from a form, the data property is not null, therefore the reason for the new item creation in the database.
There are many ways to solve this. One of them is to remove that check from the *edit_gallery* method, create another method like *save_gallery*, and call that method from *edit_gallery.ctp*.
So the *edit_gallery.ctp* form would look something like:
<?php
echo $this->Form->create(false,array('url' => array('controller' => 'admins', 'action' => 'save_gallery')));
(your form info)
echo $this->Form->end(__('Submit', true));
?>

Categories