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

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'.

Related

Symfony2, dynamically refresh form choices

I am creating a simple Blog system with symfony2. Each blog Post is bound to a certain amount of Tags.
Tags can be selected with checkboxes when creating a new blog post. Now I want to be able to dynamically add new tag-checkboxes to the form.
The AJAX part is done and working, I can add new tag names to the Tag entity and append the new checkboxes to the form.
The problem is when I submit the form, symfony2 doesn't recognize the new added tags because they don't belong to the Tag entity yet (at the time the form was generated).
For example: after submitting the form, I dump:
$tags = $form->get('tags')->getData();
The controller ignores the tags that were added through ajax.
I know it has to be solved with events somehow, I already read this documentation: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html but can't figure out how to implement it for this specific case.
Here is my form builder for "PostType":
$builder
->add('title')
->add('content', 'textarea')
->add('tags', 'entity', array(
'class' => 'Bundle:Tag',
'property' => 'name',
'multiple' => true,
'expanded' => true,
))
->add('save', 'submit')
;
You can try to use this: Form Collection
Make sure you persist the newly added Tags before submit the form, and the checkboxes has the right names and values.
Names should be like "post[tags][]" and values should be the database ids of the Tag entities.

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.

CakePHP - JsHelper - AJAX - Parse Response Data in Independent Function

I think CakePHPs JsHelper is pretty neat to use for AJAX form submissions. Normally you just set the DOM element to update with the new content and the JsHelper takes care of the rest. A normal submit button could look like:
echo $this->Js->submit('Submit', array(
'update' => '#a-div',
'url' => 'some-url'
);
Now, I want to update 2 or 3 different DOM elements and my AJAX response type will be JSON with 2 or 3 key pairs. So to my question.
How can I capture the JSON response data and pass THAT DATA to an independent callback function that I have written myself where I can parse the response and update the relevant DOM elements with the value pairs? What is the correct syntax for that? I realise I could probably skip using the JsHelper and create my own submission, but I don't want to do that in this instance.
I found the right answer:
echo $this->Js->submit(
'Lägg en i varukorgen',
array(
'url' => array('controller' => 'products', 'action' => 'ajax_basket'),
'id' => 'basket-add-submit',
'success' => 'myFunction(data);',
)
);
At the success callback, data holds the JSON being returned.
Forget the JsHelper and write jquery code yourself.

Drupal 7 function ajax responder

I am building a complex AJAX based solution as a module into a Drupal 7 site. I decided not to write a standalone PHP script to respond to my jQUERY ajax call but implement the code within my drupal module.
My problem is establishing the connection between jQUERY and DRUPAL i:e the function which responds to my CLICK EVENT.
I was using the following code:
function staff_filter_menu(){
$items = array();
$items['staff/filtering/results/%'] = array(
'page callback' => 'staff_filter_function',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
'delivery callback' => 'staff_filter_deliver',
);
$items['staff/filtering/saveclipboard'] = array(
'page callback' => 'staff_filter_savetoDB',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
'delivery callback' => 'staff_filter_deliver',
);
drupal_flush_all_caches();
return $items;
}
But, it stopped working when I stopped, uninstalled and restarted the module. It seems to not be a reliable strategy.
drupal_flush_all_caches() does this:
Empties cache tables, rebuilds the menu cache and theme registries, and invokes a hook so that other modules' cache data can be cleared as well.
When the menu is rebuilt, hook_menu() is called...basically you're causing an infinite loop by putting drupal_flush_all_caches() where you currently have it.
You are still creating a loop where your menu items are being called, then cleared by the cache. If anything it should be called first, although there is another problem if you require this in your module's hook_menu().
You should remove that, and make sure your form is calling and returning data using fixed data.

$ajax->submit Does Not Go To Controller

I am using cakephp and pippoacl plugin and I simply cannot add a new role. What I modify in the plugin is to make the submit using ajax, something like this in my view (add.ctp):
<?php echo $ajax->submit(
'submit',
array(
'url' => array('controller' => 'roles', 'action' => 'add'),
'before' => 'beforeSubmitAdd();',
'complete' => 'completeSubmitAdd(request);'
)
);
?>
When the add.ctp gets loaded for the first time, I can print_r something from the controller. But the ajax submit above only executes the javascript on 'before' and 'complete'. I check on the firebug, the response is blank.
On my controller:
function add() {
print_r("start");
if (!empty($this->data)) {
print_r("add new role");
// save new role
}
}
I use ajax submit for user and I don't have any problem adding new user. Is there any idea where I should check? I have been comparing the user and role code for a week and I have asked a friend to look at my code, too, but we still cannot find what causes this.
Thanks in advance! :D
I am not so familiar with the Ajax helper, but I haven't using it from so long that I can't remember what is it doing :).
Back to the problem.
Did you check if the requested URL in the Ajax address is correct? This should work straightforward, but it's possible that the url to be invalid.
Are you using Security component (even just adding it on the var $components variable)?. This could lead to blank screen especially if you modifying the fields in the form somehow. Try to remove it and see if it's working without.
Finally I would say how I would do it with jQuery.
Following code should do the job:
$(document).ready(function(){
$('form').live('submit', function(){ //handles also dynamically loaded forms
var form = $(this).addClass('loading'); //indicate somehow that the form has been submitted
$('#content').load($(this).attr('action'), $(this).serialize(), function(){
form.removeClass('loading');
});
})
});
This will handle all submits in the forms of the system, but you can modify of course.

Resources