Campo de Formulario, Tipo sql
From Joomla! Documentation
El uso de este campo de formulario tipo genérico obliga a escribir código SQL en un archivo XML y es bastante limitado. Para obtener más flexibilidad, considere la posibilidad de crear su propio campo de formulario tipo por medio de subclases de la clase JFormField.
El campo de formulario, tipo sql proporciona una lista desplegable de las entradas obtenidas mediante la ejecución de una consulta a la Base de datos de Joomlaǃ. Si el campo tiene un valor guardado, este es seleccionado cuando la página se carga por primera vez. Si no, el valor predeterminado (si existe) es seleccionado.
- type (obligatorio) debe ser sql.
- name (obligatorio) es el único nombre del campo. Este debe coincidir con el nombre de la columna de los resultados de la consulta, que contendrá los valores que se mostrarán al usuario en la lista desplegable, a menos que un nombre sea especificado en el atributo value_field.
- label (obligatorio) (traducible) es el título descriptivo del campo.
- query (obligatorio, si no usa los atributos sql_*) es la consulta de SQL que proporcionará los datos para la lista desplegable. El resultado de la consulta tendrá dos columnas; una llamada 'value' (a no ser que sea sobrescrita por el atributo key_field) el cuál contendrá los valores de los elementos de lista; la otra es llamada igual que el atributo name (a no ser que sea sodrescrito por el atributo value_field) que contendrá el texto a ser mostrado en la lista desplegable.
- default (opcional) es el valor predeterminado. Este es el valor de la columna 'value', a menos que sea reemplazado por el atributo key_field.
- description (opcional) (traducible) es el texto que será mostrado como un texto de ayuda cuando el usuario mueve el ratón sobre el cuadro de lista desplegable.
- multiple (optional) turns the field into a multi-selector. Use multiple="multiple".
- key_field (opcional) es el nombre de la columna que contendrá los valores para el parámetro. Si se omite, la columna denominada 'valor' va a ser utilizada, si es que existe.
- value_field (opcional) es el nombre de la columna que contendrá los valores a ser mostrada al usuario en la lista desplegable. Si se omite, la columna con el mismo nombre que el atributo name va a ser utilizada, si es que existe.
- translate (opcional) traducirá la salida del value_field si se establece en true. El valor predeterminado es false.
- header (optional) (translatable) will add an entry, with an empty value, at the top of the list of options. This is usually used to add a "- Select something -" entry to the list. See the examples for an alternative way of achieving this.
- sql_select (mandatory if not using the query attribute) is the SELECT clause of the SQL statement. Only one such clause is permitted.
- sql_from (mandatory if not using the query attribute) is the FROM clause of the SQL statement.
- sql_join (optional) is the LEFT JOIN clause of the SQL statement. Only one such clause is permitted.
- sql_where (optional) is the WHERE clause of the SQL statement. Only one such clause is permitted.
- sql_group (optional) is the GROUP BY clause of the SQL statement.
- sql_order (optional) is the ORDER BY clause of the SQL statement.
- sql_filter (optional) filters the list by the value of another field. A field name or a comma-separated list of field names can be given. The field names must correspond to column names in the database table being queried. See the examples for further explanation.
- sql_default_{FIELD_NAME} (optional) is the default value used by the sql_filter attribute when the value of the {FIELD_NAME} filter has not been set. See the examples for further explanation.
Ejemplo de definición de parámetros XML:
<field
name="title"
type="sql"
default="10"
label="Select an article"
query="SELECT id AS value, title AS text FROM #__content"
/>
Ten en cuenta que una cláusula AS se ha utilizado en este ejemplo debido a que la tabla jos_content no tiene una columna llamada 'value'. En realidad muy pocas tablas en la base de datos de Joomlaǃ tiene una columna llamada 'value'. Alternativamente, puedes utilizar el atributo key_field para definir la columna a ser utilizadoa en lugar de 'value':
<field
name="title"
type="sql"
default="10"
label="Select an article"
query="SELECT id, title FROM #__content"
key_field="id"
/>
Esto dará resultados idénticos al ejemplo anterior.
Para ambos nombres de columna puede ser necesario un alias. Por ejemplo, supongamos que quierea que tu campo se llame 'myfield' en lugar de 'title' en el ejemplo anterior. Entonces puedes hacer esto:
<field
name="myfield"
type="sql"
default="10"
label="Select an article"
query="SELECT id AS value, title AS myfield FROM #__content"
/>
O alternativamente:
<field
name="myfield"
type="sql"
default="10"
label="Select an article"
query="SELECT id, title FROM #__content"
key_field="id"
value_field="title"
/>
También se puede ensamblar o calcular los campos en la instrucción SQL. Por ejemplo, supongamos que se desea unir la fecha/hora de cada artículo con el título del artículo en la lista. A continuación, puede utilizar esta instrucción SQL:
SELECT id, concat( title, ' (', created, ')') AS title FROM #__content
También puedes especificar una opción estática en el XML usando la etiqueta <option></option>. Por favor mira el siguiente ejemplo.
<field
name="myfield"
type="sql"
default="10"
label="Select an article"
query="SELECT id, title FROM #__content"
key_field="id"
value_field="title"
required="true"
>
<option value="">Please select your option</option>
</field>
Alternatively, you can achieve the same result using the header attribute as follows:
<field
name="myfield"
type="sql"
default="10"
label="Select an article"
query="SELECT id, title FROM #__content"
key_field="id"
value_field="title"
required="true"
header="Please select your option"
/>
Alternative query syntax
Starting with Joomla 3.5, an alternative to the query attribute allows some additional features. These features are not available if the query attribute is present. For example, this field definition:
<field
name="example_group"
type="sql"
label="COM_EXAMPLE_GROUP"
query="SELECT e.* FROM #__example AS e GROUP BY name ORDER e.id ASC"
key_field="id"
value_field="name"
/>
can be expressed as:
<field
name="example_group"
type="sql"
label="COM_EXAMPLE_GROUP"
sql_select="e.*"
sql_from="#__example AS e"
sql_group="name"
sql_order="e.id ASC"
key_field="id"
value_field="name"
/>
¡La siguiente función campos vinculados como filtros actualmente no funciona! Ver Github problema 22241
One advantage to using this syntax is that it allows the use of linked fields as filters. For example, suppose you have a form containing two select lists, one called groups and the other called subgroups. The groups field is straightforward:
<field name="groups"
type="sql"
label="COM_EXAMPLE_GROUPS"
sql_select="e.*"
sql_from="#__example_groups AS e"
sql_group="name"
sql_order="e.id ASC"
key_field="id"
value_field="name"
/>
but the subgroups field includes an sql_filter attribute which refers to the groups field by name:
<field name="subgroups"
type="sql"
label="COM_EXAMPLE_SUBGROUPS"
sql_select="e.*"
sql_from="#__example_subgroups AS e"
sql_group="name"
sql_order="e.id ASC"
sql_filter="groups"
key_field="id"
value_field="name"
/>
Then if the groups field has the value 99, the following SQL statement will be executed for the subgroups field:
SELECT e.* FROM jos_example_subgroups AS e WHERE `groups` = 99 GROUP BY `name` ORDER BY e.id ASC
To filter on multiple fields, you can use a comma-separated list of filter names in the sql_filter clause. For example, if there is a filter called groups with the value 99 and a filter called categories with the value 12, then
sql_filter="groups,categories"
will produce the SQL WHERE clause:
WHERE `groups` = 99 AND `categories` = 12
You can also define a default value for any filter that might not have a value when the field is evaluated by adding sql_default_{FIELD_NAME} attributes. For example, suppose that the default value for the groups filter is 0 and the default value for the categories filter is 0, then this definition:
<field name="subgroups"
type="sql"
label="COM_EXAMPLE_SUBGROUPS"
sql_select="e.*"
sql_from="#__example_subgroups AS e"
sql_group="name"
sql_order="e.id ASC"
sql_filter="groups,categories"
sql_default_groups="0"
sql_default_categories="1"
key_field="id"
value_field="name"
/>
will produce this SQL statement when initially evaluated with no filters:
SELECT e.* FROM jos_example_subgroups AS e WHERE `groups` = 0 AND `categories` = 1 GROUP BY `name` ORDER BY e.id ASC
Nota: Las instrucciones SQL tendrán que ser correctas para el tipo y la versión de la base de datos subyacente que Joomlaǃ está ejecutando. Lo más probable sea una versión de MySQL, pero podría ser algo más. No hay capacidad para consultar bases de datos distintas de la propia que Joomlaǃ está ejecutando.
Nota: Como se muestra en estos ejemplos, el prefijo de base de datos (a menudo jos
) se debe introducir en el formulario como #__
(numeral-guión bajo-guión bajo). Se sustituirá automáticamente por el prefijo de base de datos utilizado por Joomlaǃ.