Quick links: Content - sections - sub sections
EN FR

The format described here is the version 1.1, supported since Jelix v1.1.

Main structure

jForms file format is an XML document with <form> tag as root.


<?xml version="1.0" encoding="utf-8"?>
<form xmlns="http://jelix.org/ns/forms/1.1">

</form>

Under root tag, you'll declare tags referencing all of your form controls (also know as form fields). Controls parsing, checking and display will follow the order of appearance of tags in this document.

  • *Note: namespace of this format is http://jelix.org/ns/forms/1.1**

Common control properties

Identifier

Each form control must have an identifier (a name). You'll use ref attribute to set it. This Id will also correspond to a form variable whose value will reflect the user input. You'll likely use that variable in your submit action.

Example:


  <input ref="name">
  </input>

Note : In Jelix, there are methods to ease the use of DAO with forms, for automatic form-filling or data-saving. For this purpose, it is a good practice to use the same Id for DAO properties and associated form controls.

Label

Most of form controls must have a label declared through <label> element:


  <input ref="name">
    <label>Your name</label>
  </input>

You have the option of using a locale attribute instead of an hardcoded string :


  <input ref="name">
    <label locale="mymodule~forms.input.name"/>
  </input>

It is possible to indicate an alternate label wehn the value of the control is empty. This is useful when we use the form only to display data:


  <input ref="nom">
    <label>Your name</label>
    <emptyvaluelabel>No name<emptyvaluelabel>
  </input>

Required controls

If some controls are required in your form just add them a required attribute with value true.

<submit>, <checkbox>, <group>, <choice>, <hidden> and <output> controls do not support it.

Readonly controls

On rare occasions, it can be helpful to make a control readonly. Set a readonly attribute with value true on your control.

<submit> and <output> controls do not support it.

You can modify this property with the PHP object of the form.

Messages

You can declare an optional help message using an <help> tag: it will be displayed beside your control. Either write your message text in the tag content or define locale attribute.


  <input ref="birthdate" type="date">
    <label locale="mymodule~forms.input.birthdate"/>
    <help>Input your birthdate respecting this pattern yyyy-mm-dd</help>
  </input>

or

  <input ref="birthdate" type="date">
    <label locale="mymodule~forms.input.birthdate"/>
    <help locale="mymodule~forms.input.birthdate.help"/>
  </input>

In your HTML forms a question mark will be displayed at the right of the field and a click on it will show your help message (this behavior can be changed by providing an other html form genreator).

You could also declare an hint message which will be displayed as a tooltip on mouse hovering. This message is declared with an <hint> tag. See <help> tag for its content.

Error Messages

When user input is invalid on a field (it depends of its type) or just missing on a required field (see the required attribute), Jelix displays pre-defined error messages.

You can redefine those pre-defined messages with an <alert> tag. This tag must have a type attribute telling if it is an invalid message or a required message. As for helper messages, you can use either a locale or an hard-coded message.


  <input ref="birthdate" type="date">
    <label locale="mymodule~forms.input.birthdate"/>
    <alert type="required" locale="mymodule~forms.input.birthdate.error.required"/>
    <alert type="invalid ">Your input does not match a date pattern like yyyy-mm-dd</alert>
  </input>

Control class

To each element, there is a corresponding class named JformsControl*. Sometimes the corresponding class, which is responsible to initialize and check data, may do something we do not expect.

It is then possible to create a new class, inheriting from jFormsControl, and to indicate its name into an attribute controlclass.

Input fields

Text input

To declare an input field, use <input> tag. Set its ref attribute, and optionally <label>, <hint>, <alert>, <help> tags as well as readonly and required attributes. It supports also the following attributes: type, defaultvalue, size, minlength, maxlength and pattern.

defaultvalue indicates a default value displayed when form is empty. You can use "now" if your input represents a date. Default value will be the current date.

size defines field length in terms of number of chars.

maxlength and minlength declare a constraint on the input value: input value length shall be over minlength and under maxlength. Those attributes are only valid with type="string".

maxvalue and minvalue declare a constraint on the input value. Those attributes are only valid with type="integer" and type="decimal".

pattern: It should contain a regular expression, compatible with PHP and JS. This attribute is allowed only when type="string".

type defines which data format a user input shall match. On submit, a client-side javascript checking will be done, and also a server-side checking (case of javascript deactivated) with a call of check() method on the form object.

Below a list of type values and theirs constraints :

  • "string": string. Any char allowed. (default type).
  • "boolean": only two values accepted, "true" or "false".
  • "decimal": a number with or without comma.
  • "integer": an integer.
  • "hexadecimal": an hexadecimal number (digits 0-9 and letters a-f).
  • "datetime", "date", "time": respectively a date and time, a date, a time. And their patterns are "yyyy-mm-dd hh:mm:ss", "yyyy-mm-dd", "hh:mm:ss".
  • "localedatetime", "localedate", "localetime": respectively a date and time, a date, a time, but in the locale user format. For example, for a french site, date should match "dd/mm/yyyy", and for an english site "mm/dd/yyyy".
  • "url": user input must be a valid URL.
  • "email": user input must be a valid email.
  • "ipv4": an IP v4 address.
  • "ipv6": an IP v6 address.
  • "html": it can contains html element. The HTML content will be filtered on the server side (javascript code is removed, some attributes and specific elements are removed etc.), to avoid security problems like CSS, XSS etc..

A simple example :


  <input ref="email" type="email">
     <label locale="mymodule~myform.email.label" />
     <hint>Email shoud be valid</hint>
  </input>

A example with attribute "pattern"


  <input ref="url" type="string" pattern="/^[a-z0-9\-]+$/">
      <label>Url</label>
  </input>

Multiline input

To declare a multiline input field, use <textarea> tag. Set its ref attribute, a <label> element, and optionally <hint>, <alert>, <help> tags as well as readonly and required attributes. It supports also the following attributes: type, defaultvalue, rows, cols, minlength et maxlength.

defaultvalue indicates a default value displayed when form is empty. rows and cols defines respectively field width and height (as HTML textarea).

An example :


  <textarea ref="message">
     <label locale="mymodule~myform.message.label" />
     <hint>Write your message</hint>
  </textarea>

maxlength and minlength declare a constraint on the input value: input value length shall be over minlength and under maxlength.

type attribute can contains only one value for the moment : "html". Like the <input type="html"> element, the content will be filtered to remove some attributes which could contain javascript, and some specific elements (<script> for example...). If you want wywsiwyg html editing see below.

Wysiwyg HTML editor

To use an HTML editor in your form, you should use the <htmleditor> element.


  <htmleditor ref="description">
	<label>Describe the product</label>
  </htmleditor>

The default html builder of jforms uses CKEditor. You can specify an other html editor by setting the engine attribute. You can also indicate a configuration file with the config attribute, and indicates a skin with the skin attribute.

To know more about configuring a wysiwyg html editor, see the dedicated section about htmleditor.

wiki editor

You can use a textarea to edit wiki content. There is a <wikieditor> element to allow it. Generator could displays a toolbar with buttons to help to write wiki tags, and will use WikiRenderer (jWiki) to convert the content into HTML when displaying it.


  <wikieditor ref="description">
	<label>Describe the product</label>
  </wikieditor>

You can indicate a configuration file with the config attribute. To know more about how configuring this editor, read the corresponding section.

Datepickers

The element <date> and <datetime> facilitate the entry of a date as opposed to a simple <input>.


  <date ref="birthday">
	<label>Your birthday</label>
  </date>

The attribute ref is required, and you can use the attributes defaultvalue, readonly, required, and also the elements <label>, <hint>, <alert>, and <help>.

You can use some specific attributes : mindate, maxdate and datepicker. To know more about them, see the dedicated page.

About mindate and maxdate attributes, you can use an absolute date in the classical database format, like '2009-01-01', or a string which contains a format supported by the sprintf php function.

For instance, if we want a date of birth for persons aged 18 to 70 years old:


  <date ref="birth" mindate="-70 years" maxdate="-18 years">
	<label>date of birth</label>
  </date>

Other example, where we want a date between today and 2 month and one day old.


  <date ref="begin" mindate="now" maxdate="+2 months 1 day">
	<label>Begin of the event</label>
  </date>

Time picker

To allow to indicate a time, use <time>.

`

<time ref="meetingtime">
    <label>Meeting Time</label>
</time>

`

The attribute seconds="true" allows to indicate seconds.

You can set mintime and maxtime to add constraints on the time.

Password

If you want your user to input a password or any values that should be kept hidden on input, use <secret> tag. Set its ref attribute, and optionally <label>, <hint>, <alert>, <help> tags as well as readonly and required attributes.


  <secret ref="password">
     <label>Your password</label>
     <hint>Write the password you received on registering</hint>
  </secret>

You can use size attribute to indicate field size.

It is often usefull to ask your user to confirm its password entry. jForms does it automatically. You just have to add <confirm> tag as child of <secret>, and the HTML form generated will have two input fields. <confirm> tag must contain either its hard-coded label, or a locale attribute pointing to it.


  <secret ref="newpassword">
     <label>New Password</label>
     <hint>Write a new password</hint>
     <confirm>Confirm your new password</confirm>
  </secret>

Your html form will likely be:


   <label for="newpassword">New password</label>
        <input type="password" id="newpassword" name="newpassword" title="Write a new password"/>

   <label for="newpassword_confirm">Confirm your new password</label>
        <input type="password" id="newpassword_confirm" name="newpassword_confirm"/>

Checkbox (one and only)

To display a checkbox, declare a <checkbox> tag. Set its ref attribute, its <label> element, and optionally <hint>, <alert>, <help> tags as well as readonly and required attributes.


  <checkbox ref="remember">
     <label>Remember me</label>
     <help>Check this box to log in automatically next time</help>
  </checkbox>

Default values for a checkbox are 0 if it was not checked, or 1 on the contrary.

You can override those default values. Just add valueoncheck and valueonuncheck attributes (those equal respectively to 1 and 0 by default, if you follow). Example:


  <checkbox ref="remember" valueoncheck="Y" valueonuncheck="N">
     <label>Remember me</label>
     <help>Check this box to log in automatically next time</help>
  </checkbox>

Keep in mind that when you'll display a pre-filled form, your checkbox will be checked or not, on a comparison between its initial value and valueoncheck or valueonuncheck.

During the display the form data (without controls), it is better to display a specific label instead of values. You can then indicate labels corresponding to values. Use element <oncheckvalue> and <onuncheckvalue>.


  <checkbox ref="remember" valueoncheck="Y" valueonuncheck="N">
     <label>Remember me</label>
     <help>Check this box to log in automatically next time</help>
     <oncheckvalue label="yes" />
     <onuncheckvalue label="no" />
  </checkbox>

<oncheckvalue> and <onuncheckvalue> support also the attribute locale instead of label. And you can use the value attribute on it instead of using valueoncheck or valueonuncheck.

Checkboxes list

You could have to display a series of checkboxes to reflect multiple choices. For example, you want your user to select a list of articles to search or buy. Use <checkboxes> tag (with a terminal S).

Set its ref attribute, its <label> element, and optionally <hint>, <alert>, <help> tags as well as readonly and required attributes.

You'll then declare its values and their associated labels. Check further section on datasource also but here is an example:


   <checkboxes ref="food">
      <label>Check the food items you want to buy:</label>
      <item value="54">sugar</item>
      <item value="27">steack</item>
      <item value="32">orange juice</item>
  </checkboxes>

With the control above, jForms will display a list of three checkboxes, labelled "sugar", "steack" and "orange juice". On submit, the value for "food" form variable will be a PHP array. This array will contain the values of all items checked. If user has checked "steack", you'll receive array(27). If "sugar" is also checked, you'll receive array(54, 27).

(See Using the form in a controller)

Radio buttons

Radio buttons are never standalone, there must be at mininum 2 of them. To declare a set of radio buttons, use the tag <radiobuttons>.

Set its ref attribute, a <label> element, and optionally <hint>, <alert>, <help> tags as well as readonly and required attributes. As for other list controls, you must declare a list of possible values and associated labels. Check also further section on datasource.

Example :


   <radiobuttons ref="color">
      <label>What is your preferred color:</label>
      <item value="r">Red</item>
      <item value="b">Blue</item>
      <item value="g">Green</item>
      <item value="y">Yellow</item>
  </radiobuttons>

jForms will display a set of 4 radio buttons and the selected value will be stored in a "color" form variable.

To display a menu list use the tag <menulist> (<select size="1"> in HTML). A menu list allows only one choice. Set its ref attribute, a <label> element, and optionally <hint>, <alert>, <help> tags as well as readonly and required attributes. As for other list controls, you must declare a list of possible values and associated labels. Check also further section on datasource.

Example :


   <menulist ref="country">
      <label>your country is:</label>
      <item value="FR">France</item>
      <item value="US">USA</item>
      <item value="GB">Great Britain</item>
      <item value="ES">Spain</item>
  </menulist>

The selected value will be stored in a "country" form variable.

By default, if there isn't an attribute required="true", the user doesn't need to make a choice. So you have automatically a first empty choice in the list. If you want to indicate a label for this empty choice, you could use <emptyitem>.


   <menulist ref="ville">
      <label>votre ville :</label>
      
   <menulist ref="country">
      <label>your country is:</label>
      <emptyitem>-- choose a country --</emptyitem>
      <item value="FR">France</item>
      <item value="US">USA</item>
      <item value="GB">Great Britain</item>
      <item value="ES">Spain</item>
  </menulist>

Of course, you can use a locale:


      <emptyitem locale="module~foo.bar"/>

List box

Listbox (equivalent to <select> in HTML), should be declared with tag <listbox>. Set its ref attribute, a <label> element, and optionally <hint>, <alert>, <help> tags as well as readonly and required attributes. As for other list controls, you must declare a list of possible values and associated labels. Check also further section on datasource.


   <listbox ref="section">
      <label>Vote for the best doc. section:</label>
      <item value="1">Daos</item>
      <item value="2">Forms</item>
      <item value="3">Urls</item>
  </listbox>

You can also add a size attribute. It sets the number of list box items to display (hence the list box height). its default value is 4.

Listbox is one-choice only in its default behavior. However you can set multiple="true" attribute to enable multi-items selection (in an HTML form, user has to hold Ctrl key and click to select more than one element). In that situation, "section" form variable of the example above will be assigned to a PHP array of selected values instead of a single one.

File Upload

If you want user to upload a file to your server, use the tag <upload> (equivalent to <input type="file"> in HTML). Set its ref attribute, a <label> element, and optionally <hint>, <alert>, <help> tags as well as readonly and required attributes.

This control supports two specific attributes to control file type and size. Respectively mimetype (its value has to be one or more mimetype) and maxsize (size in octets).


  <upload ref="photo" mimetype="image/jpeg;image/png" maxsize="20000">
    <label>Your photo</label>
  </upload>

Upon receiving file, jForms will check its type and its size. You'll see later that you can choose where to save it. "photo" form variable will have the filename as value.

Other supported attributes:

  • accept: value of the HTML attribute accept for the element input.
  • capture: value of the HTML attribute capture for the element input.

Enhanced File Upload

The previous <upload> control, lacks of some feature to manage existing file previously downloaded, for example when the user edit data already stored with the form. You must delete yourself the old file when the user uploads a new one, you don't know which is the previous file etc.

A <upload2> is available since Jelix 1.7, and allows to support automatically existing old files. It has the same attributes and child elements as <upload>.

But it has a better associated widget, which improve the display of the control. It allows to see the name of the current selected file. It allows to replace automatically the file, or offer the choice to delete the current file (if the control value is not required).

The PHP control class offer a better API to manipulate the files:



    /** the filename sets into the form during its initialization */
    public function getOriginalFile();

    /** The filename of the file uploaded during the form submission */
    public function getNewFile();

    /** change the name of the new file name. If there is already an uploaded file, it is deleted */
    public function setNewFile($fileName);

    /**
     * Return a filename under which the file can be saved without overwriting an existing file.
     *
     * The base name of the file is the name of the uploaded file, or the name given into the $alternateName
     * parameter.
     * The returning filename can be ended by a number if there is already a file with the original name.  */
    public function getUniqueFileName($directoryPath, $alternateName = '');

    /**
     * Save the uploaded file into the given directory, under the original filename, or under the name given
     * into $alternateName
     *
     * If there is already a file with that name, it will be overwritten. If you don't want this behavior, you
     * can call getUniqueFileName to have a unique name.
    */
    public function saveFile($directoryPath, $alternateName = '');

    /** delete the current file indicated into the control */
    public function deleteFile($directoryPath);

The upload2 control offers also support on uploaded images: it displays the selected image, which is useful when the form is displayed with the "data view" mode. However, in order to display the image, the widget requires some additional attributes you give to {ctrl_control} or into the generator option widgetAttributes. These attributes help to forge the URL of the image:

  • From a selector : set parameters uriAction and uriActionParameters. If one action parameter should contain the image filename, set also the parameter uriActionFileParameter which indicate the action parameter name that will contain the image filename. If the default value of the parameter contain %s, only this %s will be replaced.
  • From a base URI : a baseURI attribute should contain the base URI of the image. The filename of the image will be append to this URI.

For uploaded images, we can also indicate the widget attributes imgMaxHeight and imgMaxWidth, which will contain the size of the displayed image (it does not change the image file).

Example:


  <upload2 ref="photo" mimetype="image/jpeg;image/png" maxsize="20000">
    <label>Votre photo</label>
  </upload>

{form $form, 'module~action', array(), 'html', array(
      'widgetsAttributes'=> array(
          'photo' => array(
                'uriAction' => 'photomanager~edit:show',
                'uriActionParameters' => array('filename' => ''),
                'uriActionFileParameter' => 'filename'
                'imgMaxWidth' => 100,
                'imgMaxHeight' => 100
          ))
       )}

{form $form, 'module~action', array(), 'html', array(
      'widgetsAttributes'=> array(
          'photo' => array(
                'baseURI' => $j_basepath.'photos/',
                'imgMaxWidth' => 100,
                'imgMaxHeight' => 100
          ))
       )}

Image upload

Since Jelix 1.7.11, <image> is a control that add more features for images than <upload2>. The associated widget allow to edit the selected image before uploading the image. The Javascript editor allow to change the size or to crop the image. It allow also to limit the size of the uploaded image. It avoid the upload of big images, which could cause memory issues during image processing in the PHP side.

The element <image> accepts the attribute ref, and you can use <label>, <hint>, <alert>, <help> as well as attributes readonly and required.

Other attributes are supported:

  • maxWidth and maxHeight: maximum size of the uploaded image. If the given have higher size, it will be resized in javascript before the upload.
  • mimetype: mime types of the authorized image format
  • maxsize: maximum size of the file
  • accept: value of the HTML attribute accept for the element input.
  • capture: value of the HTML attribute capture for the element input.

Example :


  <image ref="image" mimetype="image/jpg;image/png;" maxWidth="1024" maxHeight="860">
     <label>A photo</label>
  </image>

The associated widget accepts same attributes than the widget of upload2 : uriAction, uriActionParameters, uriActionFileParameter, imgMaxHeight and imgMaxWidth.

It accepts also these additional attributes:

  • newImgMaxWidth and newImgMaxHeight : maximum size of the image. Same feature than maxWidth and maxHeight on <image>, but use these widget attributes for dynamic values.
  • dialogWidth and dialogHeight: size of the dialog box of the image editor. Values are pixels, or "auto", so the size will be calculated based on the window size.

Grouping some controls

It can be useful to group some control, for presentation reasons or to facilitate the management of this controls with the jForms API. To do so, put all controls you want into a <group> element. This element should have a ref attribute, but can have also a readonly attribute to turn all child controls into readonly mode. Most of actions on the group control with the PHP API change properties of child controls.


  <group ref="a_group">
     <label>identity</label>
     <input ref="name"><label>Name</label></input>
     <input ref="lastname"><label>Last name</label></input>
  </group>

It is possible to add a checkbox which appears near the label of the fieldset. It allows to the user to enable or disable all controls in the group. Use the attribute withcheckbox.


  <group ref="a_group" withcheckbox="true">
     <label>identity</label>
     <input ref="name"><label>Name</label></input>
     <input ref="lastname"><label>Last name</label></input>
  </group>

Then it could be necessary, as on a <checkbox>, to:

  1. specify values of the control when the checkbox is checked or unchecked.
  2. specify the default value.

  <group ref="identity" withcheckbox="true" defaultvalue="ok">
     <oncheckvalue label="" value="ok"/>
     <onuncheckvalue label="No identity" value="no" />
     <label>identity</label>
     <input ref="name"><label>Name</label></input>
     <input ref="lastname"><label>Last name</label></input>
  </group>

<oncheckvalue> and <onuncheckvalue> support also the attribute locale instead of label.

Extended choice

Some times, we want to have a choice between many options, and for each options, to specify additional informations. jForms provides a powerful control, <choice>. This element should contain some <item> elements, and this elements contains a <label> element, but also zero or more controls.


  <choice ref="status">
     <label>Bug status</label>
     <item value="new"> <label>New</label> </item>
     <item value="res"> 
         <label>Resolved</label>
         <menulist ref="resolution">
            <label>How</label>
            <item value="0">Fixed</item>
            <item value="1">Invalid</item>
            <item value="2">Won't fixed</item>
         </menulist>
     </item>
     <item value="dup">
         <label>duplicate</label>
         <input ref="dup_bug"><label>Bug number</label></input>
     </item>
   </choice>

When a user selects one of this item (represented by radio buttons in HTML), controls of others items are deactivated.

Each <item> element should have a value attribute.

The <choice> element accept <help>, <hint>, <alert>, as well as readonly, required and selectedvalue attributes. This last attribute can contain a value of one of the items. You can also put a selected="true" attribute on an <item> element to select it.

Captcha

In some contexts, it is necessary to verify that the form is filled by a human, not by a spammer robot.

JForms provides the element <captcha> to include a field which will do this verification.

The use of the captcha element is very simple:


 <captcha ref="antispam">
    <label>Vérification anti-spam</label>
 </captcha>

To know more on this control and to configure it, see the dedicated section.

Color selector

If you want your user to select a color, use the <color> tag. Set its ref attribute, and optionally <label>, <hint>, <alert>, <help> tags as well as readonly and required attributes.


  <color ref="background">
     <label>Background Color</label>
     <hint>Select the background color of the text</hint>
  </color>

The value is a html RGB code, like #F5468D.

Submit button

In a form, you'll most of time need one or more submit buttons to validate user inputs and send form data to your server. Submit buttons are declared with tag <submit>. Set its ref attribute, a <label> element, and optionally <hint>, <alert>, <help> tags (but not readonly nor required attributes).


  <submit ref="submit">
    <label>Ok</label>
  </submit>

Its form variable will not be useful except if you have more than one submit, like the common case of "preview" and "save" action. To define more than one submit, just use item tags as in other multi-values controls. Check also further section on datasource.

Example:


  <submit ref="action">
    <label>Choose your action</label>
    <item value="preview">Preview</item>
    <item value="save">Save</item>
  </submit>

"action" form variable will equal "preview" or "save" on submit. your HTML form will display 2 buttons labelled respectively "Preview" and "Save".

Reset button

To display a reset button, use <reset> tag.


  <reset ref="init">
    <label>Reset</label>
  </reset>

Simple button

You can display a simple button, with the element <button>:


  <button ref="calc">
    <label>Calculate</label>
  </button>

It's up to you to add the javascript code in your template, to launch an action on the click event of the button.

Output values

<output> tag allows simply to display a value. It will be readonly. This could serve when you want to edit a record without allowing every field to be editable. Set its ref attribute, a <label> element, and optionally <hint>, <alert>, <help> tags (but not readonly nor required attributes).


  <output ref="category">
    <label>Category</label>
  </output>

Hidden field

If you want to include hidden fields into your form (which is equal to <input type="hidden"> in HTML), you should use the <hidden> element. It must have a ref attribute, and you can also use the defaultvalue attribute.


  <hidden ref="product_id" />

Data sources

<menulist>, <listbox> and <radiobuttons> and <checkboxes> controls each define more than one choice. you must indicate jForms how to collect values and labels of those choices.

jForms offers three ways to declare them:

  1. choices can be hard-coded in XML file (static data)
  2. choices can be retrieved through DAO.
  3. choices can be retrieved through a class.

Static choice

A choice is defined by an <item> tag. Its value is declared with the value attribute. Its label is simply the content of <item>. Alternatively you could use a locale by setting locale attribute. When label is empty, jForms takes the choice value as label.


   <checkboxes ref="objects">
      <label>You have </label>
      <item value="house">A house</item>
      <item value="car" locale="mymodule~myform.item.car.label" />
      <item value="boat"/>
  </checkboxes>

Dynamic data through DAO

List choices can be filled through a DAO. To achieve this, you have to use a <datasource> element with at least 3 attributes:

  1. dao, its value must be a dao selector
  2. method, its value select a dao method retrieving choices
  3. labelproperty, its value select a property to be used as label choices

You can use also a profile attribute to indicate the jDb profile to use.

Each value choice will be the primary key property of the selected DAO. However, you can use another DAO property by setting the valueproperty attribute.

Example:


  <menulist ref="conf">
      <label>Select which element to edit</label>
      <datasource dao="testapp~config" method="findAll"
                  labelproperty="cvalue" valueproperty="ckey"/>
  </menulist>

Indicating a DAO method with arguments

If you want to use a dao method which needs parameters, you have to indicate them with the criteria attribute or the criteriafrom attribute.

You use the criteria attribute for "static" parameters:


   <datasource dao="testapp~config" method="findAll" criteria="admin"
              labelproperty="cvalue" valueproperty="ckey"/>

Here the method findByCat() will be called with the "admin" value as parameter.

For the display of values

When the form is displayed with plugins {formdata} or {formdatafull}, where only values are displayed (or more exactly, corresponding labels), jForms don't call the method indicated into method. By default, it calls the get method of the dao, with the selected value. If there are some criterias, they are also passed to the method. It means that //the selected value and criteria values must correspond to the primary key// of the corresponding record.

However, it is not always the case. These values could correspond to other fields of the record. You have then to indicate an other method than get, which allows to retrieve the record. This method should accept the selected value and all criterias, as parameters. Indicate the name of the method into the attribute labelmethod. The method should return only one record (type selectfirst).

Multiple values in attributes

You can set several values in the following attributes:

  • labelproperty
  • criteria
  • criteriaFrom

Values should be separated by a comma.

Since labelproperty can display many values, it is necessary to indicate the separator which will be used to display this values. You then use the labelSeparator attribute.

Let's improve the previous example: we want to display the list depending on date and a category, and we want to display the label like name = value:


  <input ref="date">
     ...
  </input>
  <menulist ref="catlist">
     ...
  </menulist>
 
  <menulist ref="conf">
      <datasource dao="testapp~config" method="findByCatAndDate" criteriafrom="catlist,date"
                  labelproperty="cname,cvalue"  labelseparator=" = " valueproperty="ckey"/>
  </menulist>

Dynamic data through a class

If a DAO doesn't suit your needs, you can use a class. This class should inherit from jIFormsDatasource interface and stored in classes/ folder of a module. You'll declare this class with the <datasource> element and the class attribute.

Class example:


class listDatas implements jIFormsDatasource
{
  protected $formId = 0;

  protected $datas = array();

  function __construct($id)
  {
    $this->formId = $id;
    $this->datas = array(0 => 'test',
                         1 => 'test 2',
                         2 => 'Id = '. $id);
  }

  public function getData($form)
  {
    return ($this->datas);
  }

  public function getLabel($key)
  {
    if(isset($this->datas[$key]))
      return $this->datas[$key];
    else
      return null;
  }

}

In jForms XML file:


  <menulist ref="icon">
        <label locale="elements.crud.label.icon" />
        <datasource class="mymodule~listData" />
  </menulist>

Dependencies with an other control

In a field which have a dynamic datasource, you often may want that the list of items depends of the value of an other field. Example: a list of town depends of a country selected in an other field.

You should then use the attribute criteriafrom, which must contain the identifier of the control containing the value that serves as criteria for the list of choices.


  <menulist ref="countries">
     ...
  </menulist>
 
  <menulist ref="towns">
      ...
      <datasource dao="testapp~towns" method="findByCountry"
            criteriafrom="countries" labelproperty="town_name" valueproperty="town_code"/>
  </menulist>

In this exemple, the content of the second list will be filled depending of the selected value of the first list.

In the web page, the content of the menulist is replaced dynamically when the user change the value of the control indicated into criteriafrom.

criteriafrom is supported on dao datasources as well as on class datasources.

The class must then implement the jIFormsDynamicDatasource interface (which inherits from jIFormsDatasource2). It adds two methods, setCriteriaControls($list) which accepts a list of field id, and getCriteriaControls() which returns this list.

An abstract class jFormsDynamicDatasource, implements this interface so your class can inherit from it.

Other data source

If neither DAO, class or static data are of use, see "Defining choices on a multiple choice control" in jForms usage.

If you do so, don't declare <item> element nor <datasource> element. You have to set the datasource property on the field object, with a class.

Grouped data

For <menulist> or <listbox>, you can group data into "sections". It will produce optgroup elements in HTML.

For static datasource, use the <itemsgroup> element with an attribute label or locale.


   <menulist ref="country">
      <label>Countries </label>
      <itemsgroup label="Europe">
        <item value="fr">France</item>
        <item value="gb">Great Britain</item>
      </itemsgroup>
      <itemsgroup label="Asia">
        <item value="zh">China</item>
        <item value="in">India</item>
      </itemsgroup> 
  </menulist>

For dao datasource or class datasource, you have to set an attribute groupby on the <datasource> element. For a dao datasource, groupby indicates a property of the dao which contains the label of a group on which the record belongs to. For a class datasource, the meaning of groupby will depend of the implementation of the datasource.

Preselecting values

On Controls displaying list of choices, you sometime want to select default values. Three ways to do so:

  1. add an attribute selected="true" on selected <item> tags. Only <listbox> and <checkboxes> support more than one selected item.
  2. add an attribute selectedvalue on your control tag, and set it to the value of choice. This way, you can only declare one default value.
  3. add a <selectedvalues> tag and its child <value>. This way is preferred on <checkboxes> and <listbox> control when using a dao data source.

Examples :


  <radiobuttons ref="home">
      <label>You live in</label>
      <item value="pa" selected="true">Paris</item>
      <item value="sf">San Francisco</item>
      <item value="ld">London</item>
      <item value="be">Berlin</item>
      <item value="st">Stockholm</item>
      <item value="ma">Madrid</item>
  </radiobuttons>

  <menulist ref="conf" selectedvalue="foo.bar"
                       dao="testapp~config" 
                       daomethod="findAll"
                       daolabelproperty="cvalue"
                       daovalueproperty="ckey">
      <label>Select which element to edit</label>
  </menulist>

  <listbox ref="objects" required="true" multiple="true">
      <label>You have </label>
      <item value="house">A house</item>
      <item value="car">A car</item>
      <item value="boat">A boat</item>
      <item value="plate">A plate</item>
      <selectedvalues>
           <value>house</value>
           <value>boat</value>
      </selectedvalues>
  </listbox>