User input in Kohana 3

Views: 27301Comments: 0
Web frameworks

Это перевод русскоязычного тутора про пользовательский ввод в Kohana 3

In previous tutorial we have met Views in Kohana 3. This time we’ll look at the user input in Kohana3.

What are specific helpers in Ko3 concerning of user input? I found these ones:

•     Kohana_Form

•     Kohana_Security

•     Kohana_Upload

•     Kohana_Validate

Ignore file upload for a while (and Kohana_Upload helper too), consider simple forms. What about other stuff comparing with 2.3.x branch? At least no Input library, making XSS input filtering and superglobals delivering. There are helpers forming forms, data validation and sanitization instead.

Meet it closer. Create form for data sending to the server using Kohana_Form. First add one more page to our microsite:

public function action_form()
    $this->template->title = 'Form page';
    $this->template->content = View::factory('elements/form');
    $this->template->navigation = $this->_simple_nav();

A form naturally can be built in the “elements/form” view using Kohana_Form helper (in practice you can chose your preferable instrument). Its methods are very clear, they let setting of element name, value and (optionally) other attributes. 

echo 'Write something please:<br />';
echo Form::open();
echo '<div>'.Form::hidden('hidden','form_sent').'</div>';
echo '<div>'.Form::input('text').'</div>';
echo '<div>'.Form::password('pass').'</div>';
echo '<div>'.Form::textarea('area').'</div>';
echo '<div>'.Form::label('chck[0]','item 1');
echo Form::checkbox('chck[0]','1').'<br />';
echo Form::label('chck[1]','item 2');
echo Form::checkbox('chck[1]','2').'</div>';
echo '<div>'.Form::label('radio','Choose:');
echo '<br />';
echo 'A'.Form::radio('radio','A');
echo ' or B'.Form::radio('radio','B').'</div>';
$opts = array (1=>'car', 2=> 'toy', 3=>'ball');
echo Form::select('sel',$opts).'<br />';
echo Form::submit('submit','Send');
echo Form::close();

What should we do with the form data? First need to read them — do that in previously created Controller_Welcome::action_form() method. We have not any separate lib to process superglobals $_POST, $_GET etc, so try to make this manually (it is an officially allowed practice — see forum topic). Our action_form() will begin from:

$last_input = array();
if (Arr::get($_POST, 'hidden') == 'form_sent')
    $keys = array ('text','pass','area','chck','radio','sel');
    $last_input = Arr::extract($_POST, $keys, NULL);

This code checks whether the form was sent (hidden field value should be present). If yes, get from $_POST interesting variables (into $keys array). Here we use two methods of useful Kohana_Arr helper: Arr::get(array, key, [default value]) to get one array element and Arr::extract(array, array of keys, [default value]) to get subset of array elements. Then we can push variables in our View. Replace

$this->template->content = View::factory('elements/form');


$this->template->content = View::factory('elements/form')
                                ->set('last_input', $last_input);

And do not forget to write in 'elements/form' view:

if (is_array($last_input) AND ! empty($last_input))
    $input = array();
    foreach ($last_input as $var=>$val)
        if ($val)
            $input[] = 'Variable <i>'.$var.'</i> equals: '.$val;   
    $input = implode('<br />', $input);
    echo '<div style="width: 200pt; border-style: solid dotted; border-color: #00ff00;">'.$input.'</div>';        

Working in production, you are very encouraged to sanitize received variables at least by Security:: xss_clean() method.

Now we can add some validation to our input. What are we going to validate? For example, we require two fields: ‘text’ and ‘radio’. Moreover,  ‘text’ and ‘pass’ fields should contain alphanumbers, no more than 10 ones. Quite enough.

In such a case validation can be like that (works only if $_POST presented):

$valid = Validate::factory($last_input)

In above code I initialize a new validation object by sending data array in Validate::factory(). Next add filters that trim surrounding spaces on three string fields (it’s a pity that we cannot attach filters on some chosen fields: either on alone field or on all fields – when TRUE is set instead of field name). By the way, we have not any post-filtration in Kohana 3.

After filters I added rules for three fields. Notice that Validate::rule(field, rule, parameters array) method gets parameters as array (if they exist in corresponding validation function). So even in the case of one parameter we should set it in array!


Even less handy thing (IMO) lives in Validate::rules(field, rules array) method that sets some rules to a field at once. In its ‘rules’ array keys should be the names of rule functions, values should be the parameters of these functions. And if some function does not require any parameters (for example, 'not_empty' rule), you still should set 'not_empty'=>NULL in the rules array.

Also it is worth notable that working with Unicode in alpha* rights should be explicitly turned on by 'alpha_numeric'=>array(TRUE). For me it is something oddly that UTF-tuned Kohana does not validate UTF by default. 

If validation failed we’ll want to see errors:

if ( ! $valid->check())
    $errors = $valid->errors();   

Evoking Validate::errors() without parameters – error array will contain only mistaken fields and the name of broken rule (if some rules are broken, only first will be presented).

All errors will be printed on our form page in the special block (in controller we should ->set('errors', $errors) in our View factory):

if (is_array($errors) AND ! empty($errors))
    $input_err = array();
    foreach ($errors as $field=>$val)
        $input_err[] = 'Error in field <i>'.$field.'</i> as: '.$val[0];       
    $input_err = implode('<br />', $input_err);
    echo '<div style="width: 200pt; border-style: solid dotted; border-color: #ff0000;">'.$input_err.'</div>';        

Works, but… that’s all for today!

You can download zipped application folder.

Оставьте комментарий!

Используйте нормальные имена.



Если вы уже зарегистрированы как комментатор или хотите зарегистрироваться, укажите пароль и свой действующий email. При регистрации на указанный адрес придет письмо с кодом активации и ссылкой на ваш персональный аккаунт, где вы сможете изменить свои данные, включая адрес сайта, ник, описание, контакты и т.д., а также подписку на новые комментарии.

MaxSiteAuth. Войти через loginza