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

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

Related

CakePHP modal AJAX checks not displaying in lights out box?

Ok, this might have a very simple answer but for the life of me my I can not seem to find an answer! I am signing up users from a text into a lights out box (SimpleModal) which AJAX loads a new page for an admin to sign up a user to a selected client list.
This all works without any issues at all, so long as the model checks are correct. I have two checks, one makes sure the username is unique and that the password has at lest 8 characters, code below. But when one or both of these checks are not meet, then the user is taken to the AJAX URL and the 'message' is then displayed. This is not what I need I need it to be taken back to the lights out box or set these messages as flash error message to be printed on to the screen.
Or should I remove these checks from the modal and get JQuery to check them instead?
Any ideas?
All help very welcome.....
Model Code ::
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('isUnique'),
'message' => 'Sorry but a unique username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('minLength', '8'),
'message' => 'Sorry but a password of 8 characters or more is required'
)
) ... more check follow but these are the issues....
CTP file ::
$this->layout = 'ajax';
$AddUserForm = $this->Form->create('User', array('url' => '/ADD-USER-URL-HERE'));
$AddUserForm .= $this->Form->input('username');
$AddUserForm .= $this->Form->input('password');
$AddUserForm .= $this->Form->input('role', array('options' => array('admin' => 'Admin', 'user' => 'User')));
$AddUserForm .= $this->Form->input('data_id', array('options' => array($data), 'empty'=>true));
$AddUserForm .= $this->Form->end(__('SAVE NEW USER'));
echo $AddUserForm;
In your ctp file
$('form').on('submit', function(e) {
e.preventDefault();
$.post($(this).attr('action'), $(this).serialize(), function(res) {
$('form').replaceWith(res);
})
})
can be used for validating the data using the above script,
I think this will help you for submitting the form via ajax and you can also display the error messages using the response coming from the ajax.
Hope this will help you.

drupal ajax call from click of a link in form

How do I submit a form using AJAX when clicking a link in Drupal?
function search_form($form,$form_state) {
$form['support_email'] = array(
'#theme' => 'link',
'#text' => '',
'#ajax' =>array(
'callback' => 'ajax_change',
'wrapper' => 'email-hidden',
'method' => 'replace',
'click' => 'true',
),
);
}
This is the form link I have inside a form. On clicking the link, I want the AJAX callback function ajax_change to be called, which does not seem to be happening.
The forms api reference for the #ajax functionality says that it is "Used by: button, checkbox, checkboxes, image button, password, radio, radios, select, submit, tableselect, textarea, text_format, textfield". Link is not in the list and thus won't work. The #ajax functionality makes Drupal perform an AJAX call when the specified form element changes. Since a link doesn't change, it is logical that it doesnt work.
The Asaf (ajax submit for any form) module may be able to help you to achieve what you want to do.
Also, it appears you are trying to use this AJAX to hide an element. The Forms API has a states functionality that makes it easy to conditionally show/hide elements. Read this for more info about states.
The #ajax callback is used to make a form that dynamically changes itself.
In Drupal it's not possible (without using third party modules) to use link tag as an AJAX triggering element. The alternative solution may be to create a hidden button element with AJAX functionality, and make link trigger click event on that hidden button.
Here is form function:
function mymodule__form($form, $form_state) {
// JS file contains the code for triggering click event on e hidden button.
$form['#attached']['js'][] =
drupal_get_path('module', 'mymodule') . '/js/mymodule.behaviors.js';
// Our link element.
$form['link_mymodule'] = array(
'#type' => 'link',
'#name' => 'link_mymodule',
'#title' => t('Perform mymodule logic'),
'#href' => current_path(),
'#options' => array(
'attributes' => array(
'class' => array('mymodule_ajax'),
),
),
);
// Hidden AJAX enabled submit button.
$form['mymodule_ajax_submit'] = array(
'#type' => 'button',
'#value' => 'AJAX submit',
'#name' => 'mymodule_ajax_submit',
// You may need this to disable validation.
'#limit_validation_errors' => array(),
'#ajax' => array(
'callback' => '_mymodule__form__pager_callback',
'event' => 'click',
),
'#attributes' => array(
// Class "element-hidden" will hide the button.
'class' => array('element-hidden', 'mymodule_ajax_submit'),
),
);
// Some element for tests.
$form['random_thing'] = array(
'#type' => 'markup',
'#markup' => rand(1, 10000),
// Wrapper is needed since AJAX will use it as a container for incoming data.
'#prefix' => '<div class="ajax_wrapper">',
'#suffix' => '</div>',
);
return $form;
}
You will also need callback function for replacing old data with new one since you are using AJAX:
function _mymodule__form__pager_callback($form, &$form_state) {
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_replace('.ajax_wrapper', trim(render($form['random_thing']))),
),
);
}
Also you will have to attach click event to your link, which will trigger click event on a hidden button. That's what stored in /js/mymodule.behaviors.js file.
(function ($, Drupal) {
Drupal.behaviors.mymodule = {
attach: function (context, settings) {
// Since behaviors will be executed every times AJAX is called, it's better to use $.once() method even if you
// are going to use "context" argument. That is needed to be sure that event is attached only once.
$('.mymodule_ajax', context).once('mymodule_ajax', function () {
// Bind click event to out link.
$(this).click(function (e) {
// Prevent browser to follow the link.
e.preventDefault();
// Perform click triggering.
$('input.mymodule_ajax_submit').click();
});
});
}
}
}(jQuery, Drupal));

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.

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

Why won't Drupal AHAH forms work within a block?

I'm trying to get an AJAX-submitted (AHAH) form working to display in a block on the sidebar. For testing purposes, I'm using an example module called "Poof" from the Pro Drupal Development book: http://books.google.com/books?id=VmZrdGuBZCMC&lpg=PA269&ots=cnHiYG6kXn&dq=pro%20drupal%20development%20poof&pg=PA269#v=onepage&q=pro%20drupal%20development%20poof&f=false
The only thing I've added to the example so far is an implementation of hook_block, which looks like this:
function poof_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
case 'list':
$blocks[0]['info'] = t('poof');
return $blocks;
case 'view':
$block['content'] = drupal_get_form('poof_form');
return $block;
}
}
The AJAX module works fine when displaying on its own page (mydrupalsite.com/poof) but when I call the form with module_invoke('poof', 'block' ...) in a template file, the form submits as normal (sans AJAX) and refreshes the page.
I can't find a definitive answer for why this happens, though a found something tangentially related that suggests that maybe AHAH doesn't work within blocks. If that's so, why? Or better yet, what's a work-around. Do I have to put the on its own blank page and bring it in with an iframe? That sounds unnecessarily messy.
UPDATED:
Here's more code for reference (again, it's from the Pro Drupal book)
function poof_form() {
$form['target'] = array(
'#type' => 'markup',
'#prefix' => '<div id="target">',
'#value' => t('Click the button below.'),
'#suffix' => '</div>',
);
$form['submit'] = array(
'#type' => 'button',
'#value' => t('Click Me'),
'#submit'=>false,
'#ahah' => array(
'event' => 'click',
'path' => 'poof/message_js',
'wrapper' => 'target',
'effect' => 'fade',
),
);
return $form;
}
function poof_message_js() {
$output = t('POOF!');
drupal_json(array('status' => TRUE, 'data' => $output));
}
Try adding
$blocks[0]['cache'] = BLOCK_NO_CACHE;
to your hook_block implementation.
Rendering a form with ahah causes a call to drupal_add_js to add the ahah javascript, but while the output of the block is cached, the javascript that gets added to the page doesn't.

Resources