¿Qué opinas de la librería formslib?

¿Qué opinas de la librería formslib?

by Francisco Marín Hernández -
Number of replies: 4
Después de un tiempo generando formularios con la librería formslib, he decidido no volver a usarla. Aquí, os dejo una breve descripción de ella y lo que opino. Me gustaría saber qué opinais vosotros y a ver si así conseguimos eliminar los aspectos negativos que más abajo describo y que son los que me han llevado a abandonarla para pasar a generar formularios directamente con código HTML desde PHP.

Librería PHP formslib

La librería formslib se utiliza para crear formularios en Moodle de una manera muy rápida y sin necesidad de añadir código HTML ni Javascript. Internamente, se trabaja con objetos encargados de generar todo el código del formulario, concretamente, de la clase PHP moodleform.

Definimos nuestra clase para generar el formulario (miformulario.php):

require_once($CFG->libdir.'/formslib.php');
class MiFormulario extends modleform{
public function MiFormulario(){
/* ... aquí va mi código... */
parent::moodleform();
}
public function definition(){
$mform =& $this->_form;
/* ... aquí va mi código... */
}
public function definition_after_data(){
$mform =& $this->_form;
/* ... aquí va mi código... */
}
public function validation($datos_introducidos){
/* ... aquí va mi código... */
}
}

Definimos la página en la que se generará:

require_once('miformulario.php');
$mform = new MiFormulario();
if($mform->is_cancelled()){
/* ... aquí va mi código con la acción consecuente de haberse pulsado el botón "cancelar"... */
}
else if($datos_introducidos = $mform->get_data()){
/* ... aquí va mi código con la acción consecuente de haberse validado los datos... */
}
else{
/* Generamos el formulario */
$mform->display();
}


Esta idea no es nueva y la prueba está en que internamente se trabaja con una clase bastante conocida que ya se encarga de generar el código: HTMLQuickForm. Lo que Moodle añade en la funcionalidad de esta clase es el control de la identidad del usuario en cada página y la inclusión de campos ocultos en cada formulario con los parámetros de configuración. Esto se hace con la clase MoodleQuickForm que hereda de HTMLQuickForm sobrecargando sus métodos.

Código de formslib.php:

<?php
...
require_once 'HTML/QuickForm.php';
require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
require_once 'HTML/QuickForm/Renderer/Tableless.php';
...
class moodleform{
...
var $_form;
...
function moodleform(...){
...
$this->_form =& new MoodleQuickForm(...);
...
}
...
}
class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless{
...
}
...
?>


¿Qué ventajas tiene crear formularios con moodleform?

1. La creación de formularios sin necesidad de saber HTML ni Javascript. Evidentemente, es necesario conocer PHP.
2. La creación de tipos de campos no contemplados en HTML cuya creación sin el uso de MoodleQuickForm implicaría conocer Javascript.

En la versión 2.0 a día 09/07/08 están definidos estos tipos: checkbox, file, group, password, passwordunmask, radio, select, selectgroups, submitlink, text, textarea, date_selector, date_time_selector, htmleditor, format, static, hidden, modvisible, selectyesno, modgrade, cancel, button, choosecoursefile, choosecoursefileorimsrepo, header, submit, questioncategory, advcheckbox y recaptcha.

3. Validación de campos en el cliente.


¿Qué desventajas?

1. El programador no tiene control sobre la forma en que se validan los datos introducidos (ya existe código Javascript encargado en la misma librería).
2. Personalizar la validación de los datos en el cliente obliga añadir código Javascript en el cuerpo de la página. Esto ofusca el código PHP y limita la primera de las ventajas descritas a formularios muy simples (mi concepto de formulario "simple" lo explico en el apartado de la conclusión).
3. Crear formularios con campos dispuestos en varias columnas implica al programador introducir código HTML (etiquetas <table> o <div>). La forma en que podemos introducirlo es más farragosa que haciéndolo directamente en HTML olvidando HTMLQuickForm.

$mform->addElement('html', "<table ...>"); echo "<table ...>";
$mform->addElement('html', "<tr ...>"); echo "<tr ...>";
$mform->addElement('html', "<td ...>"); echo "<td ...>";
$mform->addElement('html', "</td>"); echo "</td>";
$mform->addElement('html', "</tr>"); echo "</tr>";
$mform->addElement('html', "</table>"); echo "</table>";


4. Modificar el aspecto mediante hojas de estilo es una tarea muy engorrosa. Los métodos de MoodleQuickForm que se encargan de generar el código HTML, hacen referencia a las hojas de estilo del aspecto (theme) aplicado a Moodle. Esto implica que para darle a un formulario un aspecto diferente independiente de Moodle, tengamos que crear reglas css propias que reemplacen las creadas, al menos hasta el fin de la generación del formulario, para después deshacer los cambios y así no alterar el estilo en el resto de elementos de Moodle.


Conclusión:

La librería formslib es útil solo para generar formularios simples. Formularios con una única columna de campos cuyos datos se introducen desde el teclado o desde menús popup predefinidos en la librería (añadir menús personales implica generar código HTML desde PHP mediante "echo") y cuya validación no implique el uso de nuevas funciones Javascript (por ejemplo, un formulario de autenticación o de registro). En realidad, los formularios se pueden hacer todo lo que complejos que se desee, pero cuanto mayor sea su complejidad menor es el interés por utilizar esta librería.

Average of ratings: -
In reply to Francisco Marín Hernández

Re: ¿What do you think of the bookstore formslib?

by John White -
Franscico and all,
Intrigued, I have posted up a very crude translation...

¿What do you think of the bookstore formslib?

After a time generating forms with the bookstore formslib, I have determined not to use it again. Here, you abandonment a brief description of her and what I think. I would like to know what opinions you and to see if thus we manage to eliminate the negative aspects that further down describe and that are the ones that have carried me to abandon it to pass to generate forms directly with HTML code from PHP.

Bookstore PHP formslib

The bookstore formslib is utilized to create forms in Moodle in a way very fast and without need to add HTML code neither Javascript. Internally, it works itself with objects responsible for generating all the code of the form, concretely, of the class PHP moodleform.

We define our class to generate the form
(miformulario.php):

require_once($CFG->libdir.'/formslib.php');
class MiFormulario extends modleform{
public function MiFormulario(){
/* ... my code goes here... */
parent::moodleform();
}
public function definition(){
$mform =& $this->_form;
/* ... aquí va mi código... */
}
public function definition_after_data(){
$mform =& $this->_form;
/* ... aquí va mi código... */
}
public function validation($datos_introducidos){
/* ... aquí va mi código... */
}
}

We define the page in which will be generated:

require_once('miformulario.php');
$mform = new MiFormulario();
if($mform->is_cancelled()){
/* ... aquí va mi código con la acción consecuente de haberse pulsado el botón "cancelar"... */
}
else if($datos_introducidos = $mform->get_data()){
/* ... aquí va mi código con la acción consecuente de haberse validado los datos... */
}
else{
/* Generamos el formulario */
$mform->display();
}


This idea is not new and the test is in which internally works itself with a class enough acquaintance that already takes charge of generating the code: HTMLQuickForm. What Moodle adds in the functionality of this class is the control of the identity of the user in each page and the inclusion of hidden fields in each form with the parameters of configuration. This it is done with the class MoodleQuickForm that inherits of HTMLQuickForm overloading its methods.

Code for formslib.php:

<?php
...
require_once 'HTML/QuickForm.php';
require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
require_once 'HTML/QuickForm/Renderer/Tableless.php';
...
class moodleform{
...
var $_form;
...
function moodleform(...){
...
$this->_form =& new MoodleQuickForm(...);
...
}
...
}
class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless{
...
}
...
?>


What advantages has to create forms with moodleform?

1. The creation of forms without HTML need to know neither Javascript. Evidently, it is necessary to know PHP.

2. The fields types creation done not contemplate in HTML whose creation without the use of MoodleQuickForm would imply to know Javascript.



In the version 2,0 to day 09/07/08 are you defined these types: checkbox, file, group, password, passwordunmask, radio, select, selectgroups, submitlink, text, textarea, date_selector, date_time_selector, htmleditor, format, static, hidden, modvisible, selectyesno, modgrade, cancel, button, choosecoursefile, choosecoursefileorimsrepo, header, submit, questioncategory, advcheckbox, recaptcha.

3. Validation of fields in the client.

¿What disadvantages?

1. The programmer does not have control on the form in which the data introduced are validated (already code Javascript in charge in the same bookstore exists).

2. Personalizing the validation of the data in the client obliges to add code Javascript in the body of the page. This dazzles the code PHP and limits the first one of the advantages described to very simple forms (my concept of form "simple" I explain him in the section of the conclusion).

3. Creating forms with arranged fields in several columns implies the programmer to introduce HTML code (labels <table> or <div>). The form in which we can introduce it is more cumbersome than doing it directly in HTML forgetting HTMLQuickForm.

$mform->addElement('html', "<table ...>"); echo "<table ...>";
$mform->addElement('html', "<tr ...>"); echo "<tr ...>";
$mform->addElement('html', "<td ...>"); echo "<td ...>";
$mform->addElement('html', "</td>"); echo "</td>";
$mform->addElement('html', "</tr>"); echo "</tr>";
$mform->addElement('html', "</table>"); echo "</table>";


4. Modifying the aspect by means of leaves of style is a very difficult task. The methods of MoodleQuickForm that take charge of generating the HTML code, they refer to the leaves of style of the aspect (theme) applied to Moodle. This implies that to give him to a form an independent different aspect of Moodle, we have that to create rules css own that replace them created, at least to the end of the generation of the form, for later undo the changes and thus not to alter the style in the remainder of elements of Moodle.

Conclusion:

The bookstore formslib is useful alone to generate simple forms. Forms with an only column of whose fields data are introduced since the keyboard or from menus popup predefined in the bookstore (to add personal menus implies to generate HTML code from PHP by means of "I throw") and whose validation imply not the Javascript of new functions use (for example, a form of authentication or of registration). In reality, the forms can be done everything that complex that be desired, but as much as greater be its smaller complexity is the interest by utilizing this bookstore.

...oh well, I'm not a great deal the wiser,
but that's the beauty of freetranslation.com!


In reply to Francisco Marín Hernández

Re: ¿Qué opinas de la librería formslib?

by Mari Cruz García -
Hola, Francisco,

Me parece muy generosa tu oferta de compartir la librería con nosotros, pero creo que el lugar adecuado para este post sería el foro en español.

Has puesto el post también allí?

I just want to thank Francisco for his offering and perphaps suggest him to post it also in the Spanish speaking community.

Thanks for those who have done the translation

Regards

In reply to Mari Cruz García

Re: ¿Qué opinas de la librería formslib?

by Francisco Marín Hernández -
Hola Mari Cruz,

tienes toda la razón. He seguido tu recomendación y lo acabo de postear en el foro en español: http://moodle.org/mod/forum/discuss.php?d=101152

Muchas gracias.

P.D.: Gracias también a Jhon por preocuparse en la traducción al castellano (http://moodle.org/mod/forum/discuss.php?d=101128#p446670).