Problem when I am populating data into selectbox through ajax in Drupal - ajax

I have installed drupal 6, added some cck fields in one content type. Added two select box fields.
I am taking the selected value of parent select box and as per that selection passing relates options to next select box field using Ajax. (e.g Country -> State. When user selects country I want to pass state values into next select box.)
But when I am submitting the form it gives the following error:
"An illegal choice has been detected. Please contact the site administrator."
I don't know why it is not taking the ajaxified select box values while saving the node.
Does somebody has the solution on it. Is there any solution to handle this dynamic select options in Drupal.
Thanks in advance.

The same thing I'm working on drupal 7 and its work for me. Below is the code. Hope this help you. What I have done is on selection of car model car variant will change and the data save in the table.
function add_offer_form($form, $formstate) {
$form['add_offer_new_car_model'] = array(
'#type' => 'select',
'#required' => TRUE,
'#options' => $car_model,
'#ajax' => array(
'effect' => 'fade',
'progress' => array('type' => 'none'),
'callback' => 'variant_callback',
'wrapper' => 'replace_variant',
),
);
// Combo box to select new car variant
$form['add_offer_new_car_variant'] = array(
'#type' => 'select',
'#options' => array(),
// The prefix/suffix provide the div that we're replacing, named by #ajax['wrapper'] above.
'#prefix' => '<div id="replace_variant">',
'#suffix' => '</div>',
);
// An AJAX request calls the form builder function for every change.
// We can change how we build the form based on $form_state.
if (!empty($formstate['values']['add_offer_new_car_model'])) {
$model_id = $formstate['values']['add_offer_new_car_model'];
$rows = array();
$result = db_query("SELECT id, variant_name from {va_car_variant} where car_model_id in ($model_id,1) order by variant_name");
while ($data = $result->fetchObject()) {
$id = $data->id;
$rows[$id] = $data->variant_name;
}
$form['add_offer_new_car_variant']['#options'] = $rows;
}
}
////////////////////////////////////////////////////////
///////// FUNCTION FOR AJAX CALL BACK
function variant_callback($form, &$form_state) {
return $form['add_offer_new_car_variant'];
}

Related

Form input not cleared after ajax submission and scrolling is not going down in drupal 8

I have a form with one field and a submit button with ajax submission option like following -
public function buildForm(array $form, FormStateInterface $form_state, $id = 0)
{
$form['fieldset']['message'] = array(
'#type' => 'textfield',
'#default_value' => "",
'#required' => true,
'#attributes' => array(
'placeholder' => t('write here'),
),
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Send'),
'#attributes' => array(
'class' => array(
),
),
'#ajax' => [
'callback' => [$this, 'Ajaxsubmit'],
'event' => 'click']
);
return $form;
}
The ajax function is following -
public function Ajaxsubmit(array $form, FormStateInterface $form_state)
{
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$db_values = [
"message" => $form_state->getValue("message"),
"date_create" => date("Y-m-d H:i:s"),
];
$save = DbStorage::Insert($db_values);
//$form_state['rebuild'] = TRUE;
$response = new AjaxResponse();
$message = DbStorage::Get(["id" => $save]);
$send_id = $message->send_id;
$build = [
'#theme' => "chat_view",
'#message' => $message,
'#sender' => $send_id,
'#current_user' => true
];
$ans_text = render($build);
$response->addCommand(new AppendCommand('#mychat', $ans_text));
}
return $response;
}
Here form data submission is working fine. But input data is not cleared after submission. I tried to clear it from my javascript using -
$('#my_form input').val("");
But the problem is my javascript file is called every 3 seconds and the form input is also cleared in every 3 seconds. this is problematic for users. Is there any other way to clear the form input after the ajax submission ? Can i do anything inside Ajaxsubmit function ?
Moreover, after getting new data, the message box does not scroll down automatically. i need to use mouse to see new messages. I tried to solve it in my javascript file with the following -
$("#mychat").each( function()
{
var scrollHeight = Math.max(this.scrollHeight, this.clientHeight);
this.scrollTop = scrollHeight - this.clientHeight;
});
Again, the problem is it scrolls down to the message box every 3 seconds. if the user wants to scroll up to see previous messages, it scrolls down. so it is not user friendly. Is there any other way for scrolling down to message box for new messages and at the same time, it will not scroll down if user's mouse is scrolling up ?
Yes, there is another way to clear the form input. You can return the actual $form array from your Ajax function rather than creating an Ajax response.
A good example of how to leverage this can be found here:
https://drupal.stackexchange.com/a/211582/82623
As far as the enter key goes, you need to move 'event' => 'click' inside of your $form['actions']['submit']['#ajax'] array and uncomment it. That has worked well for me in the past. Found somebody else with a similar observation here: https://drupal.stackexchange.com/a/29784/82623

Not saving data when add multiple select attribute in product grid

I have created one custom module with add associated products concept. Created successfully. And Its working well.
But when i add "Multi select attribute" column in product grid with that option values, That entity value not saved.
If i removed that option values from that brand attribute drop down, Its saving fine.
I have shown my code below what i did for add multi select attribute column in product grid
under _prepareColumns() method
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'brand'); // attribute code here
foreach ( $attribute->getSource()->getAllOptions(true, true) as $option)
{
if($option['value'] != '')
$valArr[$option['value']] = $option['label'];
}
$this->addColumn('brand', array(
'header'=> Mage::helper('catalog')->__('Brand'),
'align' => 'left',
'index' => 'brand',
'type' => 'options',
'options' => $valArr,
'renderer' => 'Mage_Adminhtml_Block_Catalog_Product_Renderer_Brands', // Will have to create the renderer.
'filter_condition_callback' => array($this, '_filterBrandCondition')
));
When i hide 'options' => $valArr, , All are working fine.
I can't able to understand, why its happening. Please suggest me your ideas. Thanks in advance.
Have you already created the _filterBrandCondition function ?
What Mage_Adminhtml_Block_Catalog_Product_Renderer_Brands look like ?

Unable to retain values of dependent select box in Drupal 7

I have two dependent dropdown one for country and one for state. I am using the concept multiple times in a multistep webform.
When the form loads, the list of country is okay. On selecting a particular country the state list is also okay.
Now comes the issue:
If there is some mandatory field in the same part of webform, and the user does not fill that up the form refreshes and loses the entire list of states. Also, when moving to the next step (Multi step webform) and coming back to the same page the value is lost.
However in the entire process the value of country select list is retained.
The select options generated using ajax are not retained.
Thanks in advance. Below is the code used.
$form['submitted']['employment_history']['employer_1']['address_of_employer']['country']['#ajax'] = array(
'callback' => 'my_custom_ajax_callback_for_employer_one',
'wrapper' => 'edit-submitted-employment-history-employer-1-address-of-employer-state',
'method' => 'replace',
);
/*
* Implements Ajax callback for populating list of provinces (Employer One).
*/
function my_custom_ajax_callback_for_employer_one($from, $form_state) {
$selected_country = $form_state['values']['submitted']['employment_history']['employer_1']['address_of_employer']['country'];
$states = location_get_provinces($selected_country);
$form['submitted']['employment_history']['employer_1']['address_of_employer']['state']= array(
'#type' => 'select',
'#options' => $states,
'#attributes' => array('id' => 'edit-submitted-employment-history-employer-1-address-of-employer-state'),
);
$form['rebuild'] = TRUE;
return $form['submitted']['employment_history']['employer_1']['address_of_employer']['state'];
}
My initial thought is that you should be passing the form and form state by reference ($from, $form_state) should be (&$form, &$form_state) on your ajax callback (as well you have a typo).

Drupal AJAX Replace

I'm creating a custom user settings page. I have one field: zip_code that get's it's initial value from a custom user field. I have a custom function that pulls external data using the value of the zip_code.
I currently have the default value of the field set to the custom user field (if it's available). This is working as designed; however, I want to give the user the ability to change their zip code via an Ajax callback. This would replace the already populated radio buttons with new ones. I can't seem to wrap my head around this. Here's my code:
function settings_shopping_form($form, &$form_state) {
include_once "external.inc";
// Get user fields
global $user;
$user_fields = user_load($user->uid);
$zipcode = $user_fields->zip_code['und']['0']['value'];
if(isset($zipcode)) {
$form['zip_code'] = array(
'#title' => t('Zip Code'),
'#type' => 'textfield',
'#required' => TRUE,
'#default_value' => $zipcode,
'#ajax' => array(
'callback' => 'settings_form_callback',
'wrapper' => 'textfields',
),
);
$storename = getmystorename($zipcode);
if(count($storename) > 0) {
$form['textfields'] = array(
'#prefix' => '<div id="textfields">',
'#suffix' => '</div>',
'#type' => 'fieldset' );
$form['textfields']['stores'] = array(
'#type' => 'radios',
'#title' => t('Choose your store:'),
'#options' => $storename,
'#default_value' => $storename[1], );
} else {
$form['textfields']['incorrect'] = array(
'#title' => t('Sorry, there are no stores available near you. Check back later'),
'#type' => 'fieldset', );
}
}
My callback function is very simple:
function settings_form_callback($form, $form_state) {
return $form['textfields'];
}
To reiterate: I want to add the ability to replace the populated radio buttons with new buttons generated by the getmystorename function when the zip_code field is changed.
I ended up taking an example from the examples module (love it!):
$defaults = !empty($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $zipcode;
$storename = getmystorename($defaults);
I put this before the start of my form so that the values load before the form builder.

ajax is not working in drupal 7 while using edit section

I'm also using drupal-7 and create a module. A form in which there are 2 drop downs. On selection of car model (1st drop down) car variant (2nd drop down) value will change. It work perfectly when I am creating new one. But once I go to edit some value it shows me error.
===========================================================================
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /vehicle_ades/?q=system/ajax
StatusText: Service unavailable (with message)
ResponseText: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ajax' in 'where clause':
SELECT heading,details,value_of_offer,exchange_offer,total_savings,car_model_id,car_variant_id FROM {va_offer} where id = ajax; Array ( )
===========================================================================
How do I pass car model id to ajax function
I'm working on drupal 7. Below is the code. What I have done is on selection of car model car variant will change and the data save in the table.
function add_offer_form($form, $formstate) {
$form['add_offer_new_car_model'] = array(
'#type' => 'select',
'#required' => TRUE,
'#options' => $car_model,
'#ajax' => array(
'effect' => 'fade',
'progress' => array('type' => 'none'),
'callback' => 'variant_callback',
'wrapper' => 'replace_variant',
),
);
// Combo box to select new car variant
$form['add_offer_new_car_variant'] = array(
'#type' => 'select',
'#options' => array(),
// The prefix/suffix provide the div that we're replacing, named by #ajax['wrapper'] above.
'#prefix' => '<div id="replace_variant">',
'#suffix' => '</div>',
);
// An AJAX request calls the form builder function for every change.
// We can change how we build the form based on $form_state.
if (!empty($formstate['values']['add_offer_new_car_model'])) {
$model_id = $formstate['values']['add_offer_new_car_model'];
$rows = array();
$result = db_query("SELECT id, variant_name from {va_car_variant} where car_model_id in ($model_id,1) order by variant_name");
while ($data = $result->fetchObject()) {
$id = $data->id;
$rows[$id] = $data->variant_name;
}
$form['add_offer_new_car_variant']['#options'] = $rows;
}
}
//////////////////////////////////////////////////////// ///////// FUNCTION FOR AJAX CALL BACK
function variant_callback($form, &$form_state) {
return $form['add_offer_new_car_variant'];
}

Resources