Content type is not saved when altering the node add form - ajax

Here, I have alter the add content type form as follows:
function hc_listings_form_alter(&$form, &$form_state, $form_id)
{
// print_r($form_id);
if($form_id =='home_care_popular_search_region_node_form'){
dpm($form,'form');
$selected_states=hc_listings_load_agecare_regions();
// dpm($selected_states,'selected');
reset($selected_states);
$first_state = key($selected_states);
// dpm($first_state,'$first_state');
$form['field_popular_state']=array(
'#type' => 'select',
'#default_value' => array_shift($selected_states),
'#title' => t('Popular State'),
'#description' => t('Home Care Popular State'),
'#options'=>hc_listings_load_agecare_regions(),
'#ajax'=>array(
'callback'=> 'hc_popular_region_form_ajax',
'wrapper'=> 'regions_list',
'event'=>'change',
'method'=>'replace',
),
'#required' => TRUE,
);
$form['field_popular_region']=array(
'#type' => 'container',
'#tree'=>TRUE,
'#prefix'=>'<div id="regions_list">',
'#suffix'=>'</div>'
);
$form['field_popular_region']['list']=array(
'#type' => 'checkboxes',
'#title' => t('Popular Search Regions'),
'#description' => t('Home Care Popular Search Regions'),
'#options'=>get_popular_regions($first_state),
'#required' => TRUE,
);
}
}
And the ajax Callback function is as follows:
function hc_popular_region_form_ajax($form, &$form_state){
if(isset($form_state['values']['field_popular_state'])){
$state=$form_state['values']['field_popular_state'];
hc_my_log($state);
$form['field_popular_region']['list']=array(
'#type'=>'checkboxes',
'#title'=>'Popular Search Regions',
'#description'=>'Home Care Popular Search Regions',
'#options'=>get_popular_regions($state)
);
hc_my_log($form['field_popular_region']['list']);
$form['field_popular_region']['list']=form_process_checkboxes($form['field_popular_region']['list']);
}
// $form_state['rebuild'] = true;
return $form['field_popular_region'];
}
This works but when the ajax callback is called it will execute the dpm($form,'form') (line:5) too. What is the reason for this?
And after that when I am submitting the form by clicking the default Save button in the node add form both popular regions and popular states values are not saved. What will be the cause of that? Should I have to alter the submission of the node too ?

Here ,I have altered the form fields in a wrong way so in the form submission it alerts me with errors saying that the form structure has been changed in my altering.
The error is that it is not directly targetting the specific form field..so it should be corrected as follows:
if($form_id =='home_care_popular_search_regions_node_form'){
$selected_states=hc_get_states();
reset($selected_states);
$first_state = key($selected_states);
dpm($first_state,'$first_state');
$state= (isset($form_state['values']['field_popular_state']['und'][0]['tid']))?$form_state['values']['field_popular_state']['und'][0]['tid']:$first_state;
//popular states field altering
$form['field_popular_state']['und']['#default_value']=$selected_states[$first_state];
$form['field_popular_state']['und']['#options']=$selected_states;
$form['field_popular_state']['und']['#ajax']['callback']='hc_popular_region_form_ajax';
$form['field_popular_state']['und']['#ajax']['wrapper']='regions_list';
$form['field_popular_state']['und']['#ajax']['method']='replace';
$form['field_popular_state']['und']['#ajax']['event']='change';
//popular regions field altering
$form['field_popular_region']['und']['#prefix']='<div id="regions_list">';
$form['field_popular_region']['und']['#suffix']='</div>';
$form['field_popular_region']['und']['#options']=hc_get_popular_regions($state);
}
Ajax callback is as follows:
function hc_popular_region_form_ajax($form, &$form_state){
return $form['field_popular_region'];
}
Note: the method hc_listings_load_agecare_regions() has been changed to hc_get_states()

Related

Drupal ajax form, partial render

Good day.
I created custom form in my module and defined submit button like this:
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#ajax' => array(
'callback' => 'fmg_addbanner_ajax_callback',
'method' => 'replace',
'wrapper' => 'banner_add_wrapper'
)
);
Then outputted my form like this:
$form = drupal_get_form('fmg_banner_add_form', $region_id);
print render($form);
But ajax requests don't work. I think because of there are no needed drupal js files. How can I solve this problem? Thanks.
The normal case will be to have #ajax attached to a common input, like checkbox, text box etc.
The behavior is that when user change the input value, it'll fire your callback through ajax and send entire form over, and then you can process this form behind the scene and adjust certain things before sending the form back and change the element to the wrapper you defined.
One of the question that I had for partial form rendering is when I need to do some ajax call or inject partial form element to certain area of the page while keeping the integrity of the form rendering. (I don't know exactly what form build did, i guess i don't want to know)
Since form rendering uses the renderable array, if you just want to extract certain element, you could just do
$form = drupal_get_form('application_form');
$body = render($form['body']);
The following is a real example that i took a form and split into header, footer and the rest of form elements.
// get a form for updating application info.
$form = drupal_get_form('pgh_awards_review_application_form', $app);
$elements = array();
$form_render = render($form);
$elements = array(
'qualify' => render($form['qualify']),
'threshold_met' => render($form['threshold_met']),
'submit' => render($form['submit']),
);
if (preg_match('/<form.+div>/', $form_render, $matches)) {
$elements['header'] = $matches[0];
}
if (preg_match('/<input type="hidden".+form>/s', $form_render, $matches)) {
$elements['footer'] = $matches[0];
}
$vars['form'] = $elements;
It's definitely not pretty approach, it just serves the needs at the moment.

Update area outside of CGridView via Ajax

I'm working with CGridview and updating the grid after an Ajax call. However before I get into the grid I have a a small title and a count $model->itemCount identifying how many records there are. How would I additionally try to update this piece of information along with the grid. Would it be a separate JS call?
Appreciate any help
This is my current code for the grid
'click'=>"function(){
$.fn.yiiGridView.update('item-grid', {
type:'POST',
url:$(this).attr('href'),
success:function(message) {
$('#Ajax-Flash').html(message).fadeIn().animate({opacity: 1.0}, 3000).fadeOut('slow');
$.fn.yiiGridView.update('item-grid');
}
})
return false;
}",
Not sure is this what yoy want but you can use beforeAjaxUpdate() in CgridView as shown below
<?php
$this->widget('zii.widgets.grid.CGridView', array('id'=>'insurance_grid',
'beforeAjaxUpdate'=>"function(id, data){
//Your code to update the title and count
}",
'dataProvider'=>$model->search(),
//'filter'=>$model,
'summaryText' => '', // 1st way
'template' => '{items}{pager}', // 2nd way
'selectableRows' => 2,
'selectionChanged' => "
function(id){
}",
'columns'=>array(array('id'=>'selectedCompanies',
'class'=>'CCheckBoxColumn',
array('name'=>'Agency Name',
'type'=>'raw',
'value'=>'$data->agencyname',
),
),
));
?>

How to use ajax on a field widget submit button in Drupal 7 without validating the rest of the form

I'm making a new widget for taxonomy term references where a submit button makes an ajax call back to drupal to alter the form. Here's what I have:
$element['my_module_wrapper']['add'] = array(
'#type' => 'submit',
'#value' => t('Add'),
'#ajax' => array(
'callback' => 'my_module_ajax',
'wrapper' => $field_name . '_my_module_container',
),
);
I have the ajax call working properly, but it validates the whole form, and throws errors when unrelated fields that are required aren't filled out. How can I stop this?
Also possibly related, it doesn't seem to call my hook_field_widget_form() function when ajax is called... is this stemming from the same problem?
Have you tried making your field #type = 'button' instead of 'submit'? As far as I know, a submit button will always run through the for validate array whether it's an ajax form item or not.
Look at the example from Poll module given here: http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/7#ajax
The full function shows how it's done with '#limit_validation_errors'.

Drupal Webform Validation (webform_form_alter)

I'm doing some webform validation using webform_form_alter. I'm using webform_form_alter because I switch certain content on a "select" field.
In my webform-form-317.tpl.php I defined new fieldsets I set my fields into this new fieldset and unset the original from the webform.
$form['submitted']['ContactInfo'] = array(
'#type' => 'fieldset',
'#prefix' => '<div id="ContactInfo">',
'#suffix' => '</div>',
'#weight' => -10,
'#title' => 'Contact Information'
);
$form['submitted']['ContactInfo']['phone_home'] = $form['submitted']['phone_home'];
unset($form['submitted']['phone_home']);
in my webform_form_alter I have the following code:
switch ($form_id)
{
case 'webform_client_form_317':
{
$form['#validate'][] = 'validate_form';
}
}
My Validate_form function looks like:
function validate_form($form_id, $form_values)
{
if ($form_values['submitted_tree']['ContactInfo']['phone_home'] == "")
{
form_set_error('phone_error', t('Please enter a home phone number.'));
}
}
The issue is that the $form_values['submitted_tree']['ContactInfo']['phone_home'] comes back as nothing even is the user has inputted something into the textfield.
Any suggestions on what i'm doing wrong?
As a second question in case somebody also the answers, how do I modify the of these textfields to set the class for "form-text required error" so they show up in red with the rest of the mandatory fields.
Thanks
I hope you don't write this code in the webform module, but have made your a custom module for it.
In the first case, your function should be
function validate_form($form, &$form_state) {
if ($form_state['values']['submitted_tree']['ContactInfo']['phone_home'] == "") {
form_set_error('phone_home', t('Please enter a home phone number.'));
}
}
If you are talking about the error class, Drupal add it to all fields that has an error set like is done on the above code. You need to pass in the name of the form field as first param to the form_set_error function.

Help with ajax callback and drupal_process_form

I have a form that is added through the nodeapi displayed only on view mode. Users can select an item from a select menu and their choice will automatically get saved to the database with a hook_menu callback on change. If the user has javascript disabled, it'll submit normally with the form api. This is all working fine, but now for security reasons I want to submit the ajax version via the form api too. My form_name_submit is simple like:
function mymodule_test_form_submit($form, &$form_state) {
global $user;
db_query("INSERT INTO {mymodule} (nid, uid, status, created) VALUES (%d, %d, %d, " . time() . ")", $form['#parameters'][2], $user->uid, $form_state['values']['mymodule_status']);
}
My ajax:
$('.mysubmit').css('display', 'none');
$('.myclass').change(function() {
$.ajax({
type: 'POST',
url: Drupal.settings.basePath + 'mymodule/set/' + $nid + '/' + $('.myclass').val(),
dataType: 'json',
data: { 'ajax' : true, 'form_build_id' : $('#mymodule-form input[name=form_build_id]').val() }
});
});
And my callback function:
function mymodule_set($nid, $status) {
$form_build_id = $_POST['form_build_id'];
$form_state = array('storage' => NULL, 'submitted' => FALSE);
$form = form_get_cache($form_build_id, $form_state);
$args = $form['#parameters'];
$form_id = array_shift($args);
$form['#post'] = $_POST;
$form['#redirect'] = FALSE;
$form['#programmed'] = FALSE;
$form_state['post'] = $_POST;
drupal_process_form($form_id, $form, $form_state);
}
Originally my callback function was about the same as my submit function, but now I'm trying to use the submit function with ajax as well. Is this the right way to use drupal_process_form? The form is grabbed from the cache, it get's validated and submitted if no errors? I'm using some code from this tutorial to apply to my situation: http://drupal.org/node/331941 There doesn't seem to be any examples of what I'm trying to do. I also have $form['#cache'] = TRUE; in my form function.
How does drupal_process_form compare the submitted values with the original form to check for integrity? Am I supposed to add my values to the form_state since the form state will be empty with ajax. Been stuck on this for a few days, hopefully someone has experience with this.
Thanks.
I had to do somenthing similar to you in the past and read the same tutorial you posted, unfortunately there isn't much information avalaible about this and it was headache for me to make it work. I don't remember well the details but I was taking a look to the code I wrote and here are a couple of suggestions that may work for you:
Do not submit the form using your own jQuery code, instead use the new "#ahah" property of form elements that can be used for calling your callback in the onchange of the select http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/6#ahah
IF you are doing this in a node form, adding the #ahah property in a form alter may not work, I remember having seen an issue about this that wasn't solved at that moment. if this is the case, use this code for attaching the ahah binding, you'll not need "efect", "method" or "progress" since you just want to submit the form, not to change anything about it:
function YOURMODULE_form_alter(&$form, $form_state, $form_id) {
if ('YOURCONTENTTYPE_node_form' == $form_id) {
//the only way I could make it work for exisiting fields is adding the binding "manually"
$ahah_binding = array(
'url' => url('YOURCALLBACKPATH'),
'event' => 'change',
'wrapper' => 'FIELD-wrapper',
'selector' => '#FIELD',
'effect' => 'fade',
'method' => 'replace',
'progress' => array('type' => 'throbber'),
);
drupal_add_js('misc/jquery.form.js');
drupal_add_js('misc/ahah.js');
drupal_add_js(array('ahah' => array('FIELDd' => $ahah_binding)), 'setting');
//force the form to be cached
$form['#cache'] = TRUE;
}
}
Here is my callback function, note that it has some modifications from the tutorial you posted:
function YOURMODULE_js() {
// The form is generated in an include file which we need to include manually.
include_once 'modules/node/node.pages.inc';
// We're starting in step #3, preparing for #4.
//I have to add the 'rebuild' element, if not an empty node was created
$form_state = array('storage' => NULL, 'submitted' => FALSE, 'rebuild' => TRUE);
$form_build_id = $_POST['form_build_id'];
// Step #4.
$form = form_get_cache($form_build_id, $form_state);
// Preparing for #5.
$args = $form['#parameters'];
$form_id = array_shift($args);
$form_state['post'] = $form['#post'] = $_POST;
$form['#programmed'] = $form['#redirect'] = FALSE;
// if you want to do any modification to the form values, this is the place
// Step #5.
drupal_process_form($form_id, $form, $form_state);
// Step #6 and #7 and #8.
$form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
// Final rendering callback.
drupal_json(array('status' => TRUE, 'data' => $output));
}
As I said before there are details that I have forgot but maybe this will help you.
Good Luck.

Resources