ajax is not working in drupal 7 while using edit section - ajax

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'];
}

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

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.

CakePHP data not saving and validation not working

When my model goes to validate my form
it always come as false,
it doesn't save in the database.
I dont understand why this isn't working, it was working until I unbind on a few of my functions.
Here is my invoice model, it's supposed to check if there is to/biller in relationships_users table (relationship model).
<?php
class Invoice extends AppModel{
var $name='Invoice';
public $belongsTo = array(
'Relationship' =>array(
'className' => 'Relationship',
'foreignKey' =>'relationship_id',
)
);
var $validate = array(
'to' => array(
'relationshipExists' => array(
'rule' => array(
'relationshipExists'),
'message' => 'sorry you dont have a relationship with that user.'
),
),
);
public function relationshipExists($check){
$relationshipExists=$this->Relationship->find('count', array(
'conditions' => array(
'Relationship.partyone' => current($check),
'Relationship.partytwo' => current($check)
// get the value from the passed var
)
)
);
if ($relationshipExists>0) {
return TRUE;
}
else
return FALSE;
}
Here is my function in the invoices table
public function addinvoice(){
$this->set('title_for_layout', 'Create Invoice');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->layout='home_layout';
if($this->request->is('post')){
($this->Invoice->set($this->request->data));
if($this->Invoice->validates(array('fieldList'=>array('to','Invoice.relationshipExists')))){
$this->Invoice->save($this->request->data);
$this->Session->setFlash('The invoice has been saved');
}}else {
$this->Session->setFlash('The invoice could not be saved. Please, try again.');
}
}
What it's supposed to do is to check that to/biller are in the relationships_users table and then save the invoice to the invoice table, otherwise throw a message.
The conditions array seems strange to me:
'conditions' => array(
'Relationship.partyone' => current($check),
'Relationship.partytwo' => current($check)
// get the value from the passed var
)
That would search for Relationships with both partyone and partytwo set to to. You probably want to check if either of them is set to to:
'conditions' => array(
'OR' => array(
'Relationship.partyone' => current($check),
'Relationship.partytwo' => current($check)
)
// get the value from the passed var
)

AJAX Error Drupal-7

I am creating a module in which there is a dependency between combo boxes. There are three combo boxes: country, state, and district. If I select India in the country combo box, then the state combo box will contain all states of India, and the same in the case of district.
I have done this by using AJAX. It works properly in add form, but when I am going to update any one, the following error occurs:
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /drupal/?q=system/ajax
StatusText: Service unavailable (with message)
ResponseText: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ajax' in 'where clause': SELECT district_name, country_id,state_id FROM {ajax_district} where id = ajax; Array
(
)
in edit_district_form() (line 291 of /home/mansmu/www/drupal/sites/default/modules/ajaxtest/ajaxtest.district.inc).
My code is:
////////////////////////////////////////////////////////
///////// FUNCTION FOR EDIT
////////////////////////////////////////////////////////
function edit_district_form($form, &$form_state) {
$request_url = request_uri();
// $request_id to get id of edit district.
$request_id = drupal_substr(strrchr($request_url, '/'), 1);
//// FOR country
$rows = array();
$result = db_query("SELECT id,country_name from {ajax_country} order by country_name");
while ($data = $result->fetchObject()) {
$id = $data->id;
$rows[$id] = $data->country_name;
}
//// FOR state
$state = array();
$result = db_query("SELECT id,state_name from {ajax_state} order by state_name");
while ($data = $result->fetchObject()) {
$id = $data->id;
$state[$id] = $data->state_name;
}
// $district_name varible to get name from database for a requested id.
$district_name = db_query("SELECT district_name, country_id,state_id FROM {ajax_district} where id = ".$request_id);
// Loop For show vehicle district name in text field to be update.
foreach ($district_name as $district) {*/
$form['values']['edit_country_name'] = array(
'#type' => 'select',
// '#default_value' => "{$district->country_id}",
'#required' => TRUE,
'#options' => $rows,
'#ajax' => array(
'effect' => 'fade',
'progress' => array('type' => 'none'),
'callback' => 'state_callback_edit',
'wrapper' => 'replace_edit_state',
),
);
$form['values']['edit_state_name'] = array(
'#type' => 'select',
// '#default_value' => "{$district->state_id}",
'#required' => TRUE,
'#options' => array(),
// The prefix/suffix provide the div that we're replacing, named by #ajax['wrapper'] above.
'#prefix' => '',
'#suffix' => '',
);
$form['values']['edit_district_name'] = array(
'#type' => 'textfield',
'#size' => 30,
//'#default_value' => "{$district->district_name}",
'#maxlength' => 80,
'#required' => TRUE,
);
}
$form['edit_district_submit'] = array(
'#type' => 'submit',
'#value' => t('Update'),
);
$form['actions']['cancel'] = array(
'#markup' => l(t('Cancel'), 'district'),
);
return $form;
}
////////////////////////////////////////////////////////
///////// FUNCTION FOR AJAX CALL BACK
////////////////////////////////////////////////////////
function state_callback_edit($form, &$form_state) {
// 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($form_state['values']['edit_country_name'])) {
$country_id = $form_state['values']['edit_country_name'];
$rows1 = array();
$result = db_query("SELECT id, state_name from {ajax_state} where country_id = $country_id order by state_name");
while ($data = $result->fetchObject()) {
$id = $data->id;
$rows1[$id] = $data->state_name;
}
$form['edit_state_name']['#options'] = $rows1;
}
return $form['values']['edit_state_name'];
}
Your line of code here:
$request_id = drupal_substr(strrchr($request_url, '/'), 1);
is returning the string 'ajax', making your third SQL statement look like this:
SELECT district_name, country_id,state_id FROM {ajax_district} where id = ajax;
Obviously 'ajax' is wrong there, I guess you want a value from the URL? You could use the arg() function to extract this so you don't need to run drupal_substr etc.
If your path is ajax/12 then arg(0) will return 'ajax', arg(1) will return 12 and so on.
Hope that helps
UPDATE
If you need to save the request ID in the form do something like this in your form function:
$form['request_id'] = array('#type' => 'value', '#value' => $request_id);
Then when you get into your ajax callback you can either get it from $form_state['values']['request_id'] or $form['request_id']['#value']

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

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'];
}

Resources