My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
Formation_Documentation  
Documentation of the Formation module
Featured, Documentation
Updated Feb 4, 2010 by maartenvanvliet

Introduction

The Formation module is a replacement of the current validation library as well as the Forge library. It was created due to some specific needs of mine and developed as such. It has reached a state in which it might be beneficial to other users as well.

I would greatly appreciate feedback, comments, bugfixes etc.

You can download the latest release from http://code.google.com/p/kohana-mptt/downloads/list or checkout the latest edition from the subversion repository.

If you're looking for documentation on ModelToForm , follow the link. ModelToForm is a way to have forms generated from your models. It's a wIP.

Installation

Before installation you should know how to work with Kohana else this might become difficult.

You should extract the archive and put it into your modules folder. In your application/config/config.php you should enable this module.

Documentation

Now, you'll find several files in the formation folder: Field.php, Formation.php and Validation.php as well as a folder elements and a folder rules. As is usual in Kohana the files map to classes.

The Field class stands for an input field in a form. Elements extend from this field, such as the Input element, Password element etc.. A field has rules for validation, these rules are found in the rules folder.

The Validation class does just validation, it doesn't generate your forms. Formation class extends Validation and does generate your forms.

Note I moved rules and elements in a subfolder for clarity. This means they cannot be autoloaded by Kohana unless you register a new autoloader. The Formation or Validation class usually do this but if you want to use elements or rules outside of these classes you should register the autoloader yourself. You can find it in Validation.php

Your first form

First we use the Validation class without form generation. We have a form which has to fields 'username' and 'password'.

$_POST=new Validation($_POST);
$_POST['username']->add_rule('Rule_Required');
$_POST['password']->add_pre_filter('trim')->add_rule('Rule_Min_Length',8)->add_rule('Rule_Required');

You see, it's easy. Normally the $POST is filled by php and you use it, now you set some rules on it's keys and let it validate. If the form is submitted the constructor takes the $POST values. If not you still create the fields in your validation and add the rules. Would work for $GET as well of course.

Other methods you can carry out on a $POST field.

  • add_rules, remove_rule, clear_rules
  • add_post_filter, add_post_filters, remove_post_filter, clear_post_filters
  • add_pre_filters etc.
  • add_callback etc.
  • get_value(), set_value(), get_name(),
  • get/set_screen_name (it's the name of the field used in labels or errors)
  • error() returns array with one error with message
  • add_error() mostly used internally but might be useful for callbacks
  • remove_error()
  • error_format() supply string with {message} as message placeholder
  • get_error_format()
  • set_language_file() set language file for all rules this field has (default: validation which maps to i18n/language/validation.php
  • validate() validates the field, returns boolean first pre-filters, rules, callbacks post-filters

You can use also get and set the properties, only not name

$_POST['password']->screen_name='asdf';

You can at any time echo the object

echo $_POST['username'];

It's an array object, means you can sort it, count it, put it in a loop

$_POST->asort();
count($_POST);

Fun he

Ok, on to the Validation class

Validation class

Some of the class methods

  • add_rule, rules, clear and all that as well as for callbacks and pre/post filters so you can attach a rule to whole league of fields
  • error_format() set error format for all fields
  • validate() validates all fields
  • errors() returns array of fields with an error for each if there is one
  • validate_parial(array of fieldnames) validate form partially
  • validate_partial_json same as above just returns a json boolean
  • set_language_file() set language file for all rules in every field

$_POST=new Validation($_POST);
$_POST['username']->add_rule('Rule_Required');
$_POST['password']->add_pre_filter('trim')->add_rule('Rule_Min_Length',8)->add_rule('Rule_Required');
if($_POST->validate())
{
 echo 'have fun';
}
else
{
 var_dump($_POST->errors();
}

Again, fairly simple or not :)

Formation class

Works pretty similar to the Validation class when it comes to adding rules, filters and callbacks. Every Element inherits from the Field class so all those methods are available.

First form

$form=new Formation;
$form->set_method('POST'); //is default but still
$form->set_attr('id','form_css_id');

$form->add_element('input','username')->add_rule('Rule_Exact_Length',4);

if($form->validate())
{
  echo 'yah';
}
else
{
  echo $form; //will call $form->render()
}

You can see I create an instance of the form, set it's method and id add one element with a rule. Then I try to validate it, if it fails it renders the form.

The class renders a view with the form. This view or template can be found in formation/views/formation_template.php You can change the template with

$form->set_template('your_template');

get_template() retrieves the template.

You might have some variables in your template that you want to fill. By default there is an $legend variable. You can set variables in your template like this, just like views in Kohana.

$form->legend='your legend';
$form->some_var='some value';

Formation extends Validation so the Validation methods are also available in the Formation class.

Elements

Like seen in the example above you can add elements. Related methods

  • add_elements
  • remove_element
  • clear_elements

You can also add elements like this

$input=new Element_Input('email');
$input->class='some_class';
$input->set_attr('id','some_id')
      ->add_rule('Rule_Matches',$form['username']);

$form->add_element($input)->label()->set_text('email label ');

This means there are two syntaxes

$form->add_element(new Element_Input('name'));
$form->add_element('input','name');

Elements you can add

  • Element_Checkbox
  • Element_Checklist
  • Element_Dropdown
  • Element_Email - same as input but comes with the email rule
  • Element_Csrf - cross site request forgery protection
  • Element_Group - put some elements between
    <fieldset>
  • Element_Hidden
  • Element_Input
  • Element_Label (not really an element, is covered later)
  • Element_Password
  • Element_Submit
  • Element_Textarea
  • Element_Upload

Label

Labels are special. See example

$form->add_element('input','name')->label()->set_attr('id','someid')->set_text('some text');

label() returns an object label of which you can set the attributes and text.

Special elements

Some elements have special methods. Check the source. $form->add_element('upload','load_file')->set_directory('some_dir');

Groups

Groups also work as elements but do not extend Element_Input but Formation. The default template renders them within a

<fieldset>
element. You can nest them.

$form->add_element('input','email');
$form->add_group(array('email'),'group1');

$form['group1']->add_element('password','Password field')->add_rule('Rule_Min_Length',8);
$form['group1']->add_group(array(),'group2');
$form['group1']['group2']->add_element('input','sth');

The first argument of the add_group method can be a string or array with the names of elements, or elements themselves. If they are names they will be retrieved from the group's parents and moved to the group. Else, they will simply be added. Only the parent's elements are searched for, grandparents are not.

Groups extend Formation so many Formation methods are valid here. The default template for groups is the same as for Formation.

Rules, callbacks and filters

Callbacks and filters are all callbacks.

Rules

Rules are the following

  • Rule_Alpha
  • Rule_Alpha_Numeric
  • Rule_Array
  • Rule_Csrf - no need to call manually, is included in Element_Csrf
  • Rule_Depends_On
  • Rule_Digit
  • Rule_Email //is included in Element_Email
  • Rule_Exact_Length
  • Rule_Ip
  • Rule_Length
  • Rule_Matches
  • Rule_Max_Length
  • Rule_Min_Length
  • Rule_Numeric
  • Rule_Range
  • Rule_Regex
  • Rule_Required
  • Rule_Upload_Allowed
  • Rule_Upload_Required
  • Rule_Upload_Size
  • Rule_Url

Some accept arguments, you can also set the error message, language file. In the language files that come with Formation you can see the syntax used.

Storing forms

Using a form class you can store forms and use the throughout your application. Example: My_Form.php

class My_Form_Core extends Formation{
   public function __construct()
   {
      parent::__construct();
      $this->legend='Some legend';
      $this->add_element('input','email')->add_rule('Rule_Required');
      $this->add_element('input','username')->add_rule('Rule_Required');
      $this->add_element('submit','Submit');
   }
}

Now loading the object is as easy as $form=new My_Form; $form->render();

Example of Formation

A complete example

$form=new Formation;
		
$form->add_element('input','username')->add_rule('Rule_Exact_Length',4);

$form->add_element('upload','load')->add_rule('Rule_Upload_Size',1050);
		$form->add_element('input','email')->add_rule('Rule_Email')->add_rule('Rule_Required');
$form->add_group(array('username'),'group1');
$form['group1']->add_element('password','Password field')->add_rule('Rule_Min_Length',8);

$form->add_element('submit','Submit');
$form['group1']->legend='User/pass here please';
$form->legend='Some legend';
if($form->validate())
{
	echo 'validates';
}
else
{
	echo $form;
}	
Comment by makeWebApp@gmail.com, Apr 26, 2008

sorry, But I got the following error, Please tell me what can I do now?

Fatal error: Class 'required' not found in D:\apachefriends\xampp\htdocs\tagsmatch\modules\formation\libraries\Field.php on line 307

Thanking you

Comment by project member maartenvanvliet, Apr 26, 2008

Probably an old version of Formation. Try to add Rule_Required? instead

Comment by syndi...@gmail.com, Jul 2, 2008

I got the following error:

Fatal error: Call to undefined method Form_Field?::label() in /var/www/modules/formation/views/formation_template.php on line 21

What can it mean?

Comment by syndi...@gmail.com, Jul 2, 2008

I deleted this code and error disappeared:

$form->add_group(array('username'),'group1');
$form['group1']->add_element('password','Password field')->add_rule('Rule_Min_Length',8);

$form->add_element('submit','Submit');
$form['group1']->legend='User/pass here please';
$form->legend='Some legend';
Comment by syndi...@gmail.com, Jul 2, 2008

I think there is bug somewhere around function Formation_Core?->ordered_elements(), because after this function is called an empty form field 'username' of type Form_Field? appears in $inputs array and when Kohana renders template it causes the error.

Comment by project member maartenvanvliet, Jul 2, 2008

I'll look into it shortly. Might be related to the groups functionality. Thanks for the extensive bug reports.

Comment by legendqu...@gmail.com, Jul 30, 2008

It doesn't appear that required dropdowns aren't working.

$form->add_element('dropdown', 'field_name')->set_options(array('option1', 'option2'))->add_rule('Rule_Required?');

The validation always generates a "The field_name field is required." error message, no matter what I select when submitting the form.

Comment by Fid...@gmail.com, Aug 22, 2008

It's very usefull library, but I was confronted with the next challenge: Formation-0.98 does not work with Kohana 2.2 (old ORM and ORM2 are not compatible). Thanking you.

Comment by project member maartenvanvliet, Aug 22, 2008

Thanks, I think the svn version is up to date. I've been meaning to upload a new package but haven't gotten around to it.

Comment by ndo...@gmail.com, Sep 17, 2008

Very nice and useful library. Thank you.

For Kohana 2.2 with the latest Formation svn (Sept. 15, 2008) had to make the following changes to get rid of the Log and Config error messages: - Formation.php (34) - replace Log::add with Kohana::log - Validation.php (33) - same thing as above - Validation.php (50) - replace Config::item with Kohana::config There may be some other places, but so far I got away with just the above.

For those interested, to "ease" the creation of custom form templates (and use field names as variables in the template - similar to Forge), add these lines:

foreach ($form->inputs as $key => $value) {
$this->set_template_var($key, $value);
}
in the Formation.php render() function, immediately after this line (360):
$form->inputs = $this->ordered_elements();

Not much, but I personally find it clearer to see something like $username->render() or $username->label() in the template. If these were already there, I apologize for my lack of knowledge.

Comment by robna...@gmail.com, Oct 9, 2008

this is not working for me after all the changes I made. I able to get the form to show, but clicking submit with not values in the fields, simply returns the form with no error messages. Debug log records 'Formation library initialized'. Even when I enter valid data, it does not want to validate. Any ideas?

Comment by phpclub, Oct 20, 2008
Class 'Element_Input?' not found in /modules/formation/libraries/Formation.php on line 158
Comment by phpclub, Oct 21, 2008

Oops... Complete change of autoloading: classes are now loaded by changing underscores to slashes to create a path, eg: Controller_Admin_User? would be found at classes/admin/user.php (See routing changes below for more information)

http://dev.kohanaphp.com/changeset/3366

Comment by vorpa...@gmail.com, Mar 22, 2009

This project is still alive ? I've got hope for a new version because this version have some bugs. ie. $form->set_values don't work if elements are in groups

Comment by brudi...@gmail.com, Mar 25, 2009

I'm trying to get this working too. Validation seems to be broken. If I get it working I'll post the code.

Comment by vorpa...@gmail.com, Mar 26, 2009

I temporary solve this problem. Solution is: values must be set before grouping elements. So, if form is defined inside a library it should be done in 3 steps: 1) create form object from library, 2) settting values, 3) grouping elements. It work as expected, but looks very bad :)

Comment by project member maartenvanvliet, Mar 27, 2009

I'm sorry I haven't been able to update this project but I am just too busy. Stuff is still geared towards an old version of Kohana. If anyone wants to fork it, be my guest.

Comment by jako...@gmail.com, Apr 3, 2009

syndicut: I think the error is, that there is no label() funktion in FORMATION_CORE or Element_Group?. And i'm not quite sure what should happen, or else I could make the function myself.

Comment by jako...@gmail.com, Apr 3, 2009

How to report bugs to this project, the right way ?

There is a minor "bug" in the file: i18n/en_US/validation.php

'rule_upload_size' => 'The {filename file you uploaded was too large. The maximum size allowed is {max_bytes}.',

after {filename there should be a }

Comment by brudi...@gmail.com, Apr 13, 2009

Here's a modified version I've got working with Kohana V2.3.

http://www.citricity.com/formation_kohana_2_3.zip

Might fork this at some point with a new google code project.

Comment by meroj...@gmail.com, Oct 29, 2009

There is another error with the class Config in file libraries/elements/Element_Label?.php on line 18, replace Config::item with Kohana::config.

Comment by khai...@gmail.com, Nov 3, 2009

brudinie, i tried your version for kohana 2.3, but still the add_group() method still raised exception.


Sign in to add a comment
Powered by Google Project Hosting