Formularios AJAX en drupal 7

  • Posted on: 13 March 2014
  • By: rob

Nota:esto es un traducción/adaptación de la fuente original obtenida de drupal.org (se pretende además añadir ejemplos)

Formularios AJAX en drupal 7

Introducción a los formularios habilitados-AJAX Los formularios habilitados en Drupal 7, ofrecen un comportamieto dinámico sin la necesidad de recargar la página con cada petición, y son fáciles de crear y de manipular. Son una simple extensión de la API de formularios de Drupal (de ahora en adelante FORM API).

¿Qué es el comportamiento dinámico?.

Tradicionalmente el comportamiento de la web, hacía que el usuario tuviera que rellenar campos en un formulario y hacer click en un botón, y la página entera tenía que recargarse (lo que se conoce por hacer rebuild) y volver a cargar el navegador (recargarse la página). AJAX-enabled forms actualiza o remplaza parte de la página o parte del formulario sin necesidad de recargar la página entera, solo la parte que necesita ser cambiada es recargada (traducción no literal, pero creo que así se entiende mejor). Es más responsiva de cara al usuario y más rápido que la recarga de la página tradicional.

Algunos factores acerca de de AJAX:
  • los formularios AJAX permiten un comportamiento dinámico de los formularios sin necesidad de recargar las páginas.
  • Esto es realmente sencillo en Drupal 7.
  • Como desarrollador web, no tiene que tocar ni usar nada de Javascript (esto ha quedado en la prehistoria del desarrollo web, chiste malo de la casa :) ), Drupal 7 hace todo el trabajo por ti (así da gusto).
  • Los formularios AJAX son un pariente cercano de los formularios por pasos (multisteps forms) .
  • La mayor parte del tiempo, AJAX-enabled forms remplazan de forma dinámica partes del html de una región en la página, la cual es a menudo una pieza del formulario recargado (rebuild).
Algo de historia:
antes de Drupal 7, a los formularios AJAX se les llamaba como "AHAH forms", porque AJAX (Asynchronous JavaScript and XML) daba por sentado, que XML estaba participando en la petición, pero la técnica de Drupal no usa XML (yeahh!),  (y la parte JavaScript está entre bastidores) . En Drupal 7 la terminología fue cambiada al término común AJAX, a pesar de que no es literalmente exacta. También antes de Drupal 7, había un buen montón de magia negra necesaria para que el formulario funcionará correctamente con AJAX.  

Todo esto se ha estandarizado y "movido" dentro del código del core Drupal 7, por lo que no tienes que preocuparte por esto nunca más. Existen multitud de ejemplos de comportamientos AJAX en Drupal 7 que no tienen nada que ver con los formularios AJAX. Por ejemplo, el módulo Fivestar utiliza su propia implementación de AJAX, para comunicar un voto de el buscador al servidor sin necesidad de recargar la página. La gran idea es que tu formulario se recargue cuando interactuas con un elemento del formulario (select, submit o de cualquier otro tipo). Tu función constructora del formulario contruye de un modo distinto basándose en este input ($form_state). Tu configuración de #ajax y tu función "callback" (función llamada) se encargará de entregar la totalidad o una parte de la nueva "re-construcción" del fomulario (newly rebuild) para reemplazar o por el contrario mejorar alguna parte de la página. Lo básico para crear un AJAX-enabled form:

establece un elemento del formulariuo usando la propiedad #ajax. Este elemento del formulario disparará un llamada en segundo plano, cuando este sea haya modificado o se haya hecho click en el.

Continuará.......

The #ajax['wrapper'] property includes the HTML ID of a page section that should be replaced (or altered in some other way). The #ajax['callback'] tells the Form system what callback should be called after the AJAX call happens and the form is rebuilt. Create a callback function (named by the #ajax['callback']). This is generally a very simple function which does nothing but select and return the portion of the form that is to be replaced on the original page.

 

In the Examples Module "AJAX Example: generate checkboxes" example, the AJAX-enabled element is a select, $form['howmany_select'], which causes replacement of the HTML ID 'checkboxes-div' (named in #ajax['wrapper']), which is a wrapper around a the fieldset $form['checkboxes_fieldset']: t('How many checkboxes do you want?'), '#type' => 'select', '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4), '#default_value' => $default, '#ajax' => array( 'callback' => 'ajax_example_autocheckboxes_callback', 'wrapper' => 'checkboxes-div', 'method' => 'replace', 'effect' => 'fade', ), ); $form['checkboxes_fieldset'] = array( '#title' => t("Generated Checkboxes"), // The prefix/suffix provide the div that we're replacing, named by // #ajax['wrapper'] above. '#prefix' => '

 

', '#suffix' => '

', '#type' => 'fieldset', '#description' => t('This is where we get automatically generated checkboxes'), ); // Complete example below! ?> When the 'howmany_select' element is changed, a background request is issued to the server requesting that the form be rebuilt. After the form is rebuilt, using the changed 'howmany_select' field as input on how to rebuild it, the callback is called:

The callback in this case (and in many cases) just selects the portion of the form which is to be replaced on the HTML page and returns it. That portion of the form is later rendered and returned to the page, where it replaces the #ajax['wrapper'] which was provided. That's AJAX forms in a nutshell. A form element with the #ajax property submits a background request to the server when it is triggered by a click or change. The form gets rebuilt (on the server) by the form-builder function, and then the callback named in #ajax['callback'] is called, which selects the portion of the form to return for replacement on the original page. In more detail Here is the complete example discussed above, from the AJAX Examples in the Examples module. (This example is live and maintained. You can download the Examples modules and experiment with this example.)

t('How many checkboxes do you want?'), '#type' => 'select', '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4), '#default_value' => $default, '#ajax' => array( 'callback' => 'ajax_example_autocheckboxes_callback', 'wrapper' => 'checkboxes-div', 'method' => 'replace', 'effect' => 'fade', ), ); $form['checkboxes_fieldset'] = array( '#title' => t("Generated Checkboxes"), // The prefix/suffix provide the div that we're replacing, named by // #ajax['wrapper'] above. '#prefix' => '

', '#suffix' => '

', '#type' => 'fieldset', '#description' => t('This is where we get automatically generated checkboxes'), ); $num_checkboxes = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1; for ($i = 1; $i <= $num_checkboxes; $i++) { $form['checkboxes_fieldset']["checkbox$i"] = array( '#type' => 'checkbox', '#title' => "Checkbox $i", ); } $form['submit'] = array( '#type' => 'submit', '#value' => t('Submit'), ); return $form; } /** * Callback element needs only select the portion of the form to be updated. * Since #ajax['callback'] return can be HTML or a renderable array (or an * array of commands), we can just return a piece of the form. */ function ajax_example_autocheckboxes_callback($form, $form_state) { return $form['checkboxes_fieldset']; } ?> The form is presented to the user, as any form would be. In the form, a div with an HTML ID of 'checkboxes-div' wraps $form['checkboxes']. This is done with $form['checkboxes']['#prefix'] and $form['checkboxes']['#suffix']. If the user changes $form['howmany_select'], a background request is made to the server, causing the form to be rebuilt. The form is rebuilt, with as many checkboxes as were requested by $form['howmany_select']. ajax_example_autocheckboxes_callback() is called. It selects the piece of the form which is to be replaced on the page (almost always the same as what's in #ajax['wrapper']). The portion returned is rendered, sent back to the page, and the div with id 'checkboxes-div' is replaced on the page. Details and Warnings Changes to the form must only be made in the form builder function (ajax_example_autocheckboxes() in the example here), or validation will fail. The callback function must not alter the form or any other state. About AJAX callbacks and #default_value: When AJAX replaces form elements on the page, the form field values are not automatically populated with #default_value. However, there are other ways to set default values when using AJAX callbacks. See these links for further discussion/hints and example code: Form API: default value does not change and Default_value not working for Radio Buttons in Ajax Callback. It is possible to replace any HTML on the page, not just a form element. This is just a matter of providing a wrapper ID. You can easily replace the entire form if that is easiest. Just add a #prefix and #suffix to the entire form array, then set that as the #ajax['wrapper']. (This will allow you to change multiple form elements via a single ajax call.) The only reason not to do this is that the process is faster if less information is transferred. Keep in mind that the $form you're dealing with in your callback function has already been sent through all the form processing functions (but hasn't yet been sent to drupal_render()). So while adjusting, say, the markup of an element is straightforward:

Changing a value that has already been converted into the #attributes property means digging deeper into the $form array, as well as also changing that element's corresponding property.

Graceful degradation when the browser does not support JavaScript It is considered best practice to provide graceful degradation of behaviors in the case the the browser does not support JavaScript. AJAX forms are built for this, but it may take considerable effort to make a form behave correctly (and easily) in either a JavaScript or non-JavaScript environment. In most cases, a "next" button must be provided with the AJAX-enabled element. When it is pressed, the page (and form) are rebuilt as they are when the AJAX-enabled element is changed. The Examples module provides several examples of AJAX with graceful degradation in ajax_example_graceful_degradation.inc: An add-more button A dependent dropdown example Dynamic sections Wizard (classic multistep form) More extensive AJAX features The AJAX Framework provides many more features and options in addition to basic forms behavior. AJAX Framework Commands may be used on the server side to generate dynamic behaviors on the page. In fact, the #ajax['callback'] function may return an array of these commands instead of returning a renderable array or an HTML string. These allow general dynamic page functions that go well beyond simple Form API operations. Views module, for example, makes heavy use of these in its user interface. The #ajax['callback'] does not have to return a portion of the form. It can return any renderable array, or it can return an HTML string. The replace method is the default and most common, but it is also possible to do other things with the content returned by the #ajax['callback'], including prepending, appending, etc. It is possible to replace ajax_form_callback() with your own functions. If you do so, ajax_form_callback() would be the model for the replacement. In that case, you would change #ajax['path'] from the default 'system/ajax' and set up a menu entry in hook_menu() to point to your replacement path. Additional resources The Examples module provides the example given here, an AJAX-enabled dependent dropdown, and several other examples, including an example of graceful degradation when JavaScript is not enabled. See the AJAX Framework documentation and the Form API Reference discussion of the #ajax property.

Tags: 

Comentarios

I've been browsing on-line more than three hours these days, yet I never discovered any interesting article like <br><br>
yours. It's lovely price sufficient for me. Personally, if all site owners and bloggers made <br><br>
good content material ass you probably did, the <br><br>
web will probably be a lot more helpful than ever before.<br><br>
<br><br>
<br><br>
Here is my weblog: Internet ( http://www.flash2play.de/profil/3463/queque5.html - http://www.flash2play.de/profil/3463/queque5.html )

I've been browsing on-line more than three hours these days, <br><br>
yet I never discovered any interesting article like yours.<br><br>
It's llovely price sufficient for me. Personally,if alll site owners and bloggers made good content <br><br>
material as you probably did, the web will probably be a llot moree helpful than ever <br><br>
before.<br><br>
<br><br>
Here is my webb page ... Internet ( http://www.flash2play.de/profil/3463/queque5.html - http://www.flash2play.de/profil/3463/queque5.html )

Actually when someoje doesn't bbe aware of then its up to other users that <br><br>
theyy will help,sohere it occurs.<br><br>
<br><br>
my web site; Nutrition [ Theo - https://www.Youtube.com/watch?v=Gr4zN3KPM4s ]

Hi, I think your blog may be having wweb browser compatibility problems.Whwnever I take a look at your web <br><br>
site in Safari, it looks ffine however, if opening in IE, it has some overlapping issues.<br><br>
I just wantsd to give you a quick heads up! Aside from that, fantastic website!<br><br>
<br><br>
<br><br>
Also visit my web blog; Beauty - https://Www.youtube.com - https://Www.youtube.com/watch?v=aFKn7YMffY4 ,

Hi, I think your blog may be having web browsser compatibility problems.<br><br>
<br><br>
Whenever I take a lolk at your web site in Safari, it looks fine however,<br><br>
if operning in IE, it has some overlapping issues.<br><br>
I just wanted to give you a quick heads up! Aside from that, fantastic website!<br><br>
<br><br>
<br><br>
My web blog :: Beahty - https://Www.youtube.com - https://Www.youtube.com/watch?v=aFKn7YMffY4 ,

Añadir nuevo comentario

Plain text

  • No se permiten etiquetas HTML.
  • Las direcciones de las páginas web y las de correo se convierten en enlaces automáticamente.
  • Saltos automáticos de líneas y de párrafos.
CAPTCHA
Necesitamos saber si eres humano o un robot
10 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.