Welcome Guest, Not a member yet? Register   Sign In
Tulform form generation and validation library
#1

[eluser]Unknown[/eluser]
Hey there,

I was making a site in CodeIgniter, and, having a fair background is hard-typed languages, I wanted to use the correct abstractions. Ask in #C++ on freenode, everyone there will say copy-pasting code from one part of your project to another is always bad. Code should be unique.
With such principles in my mind, and knowing how websites generally involve copy-pasting code, I started coding. And yes, I ran into a problem: I had multiple pages with forms, and I had to copy-paste code from one form's controller-view set to another. This obviously didn't seem like the best solution and I decided to write a simple form library.

Here is the result. It's a dirty inflexible form library. It handles (or at least it's supposed to handle) form validation and converting field specifications into an HTML string.


Now, before you start using my code on your site, please be aware that this is a very rough library, it will most certainly have bugs in it (especially near the field outputting) and you'll also have to modify it to let it suit your needs and layout. I'm posting this just to either get you started, frustrated or some ideas about this subject. This code should definitely not be used it it's current form on any public website. Consequently, I am NOT responsible for any kind of damage this code or this forum message does. I have NOT thoroughly tested this code. Feel free to tell me a bug and it's corresponding fix, I might consider fixing this library, but... whatever, be careful with this library.

To use this library, add something along these lines to your controller:
Code:
$inputs=array( //Simply a 2-dimensional array of fields and their settings
            array('name' => 'name', 'string' => 'Real name'),
            array('name' => 'pass', 'string' => 'Current/new password', 'type' => 'password'),
            array('name' => 'passconf', 'string' => 'Password (confirm)', 'type' => 'password', 'validate' => 'required|matches[pass]'),
            array('name' => 'website', 'validate' => 'required|xss_clean'),
            array('name' => 'profile', 'value' => 'Update profile', 'type'=>'submit'));
        $this->tulform->setFields($inputs); //Pass fields to tulform. the 'validate' fields default to 'required'
        $disperrorous=false; //do not show error messages unless indicates otherwise below
        if($this->uri->segment(3)=="formPoster") //if the form has just been posted
        {
            $validateresult=$this->tulform->processPost(); //run validation and stuff
            
            if($validateresult===true) //validation passed
            {
                unset($_POST['passconf']); //This should not be passed to the active record functions, this field is just to help those web morons and is not saved anywhere.
                unset($_POST['profile']); //Neither does this
                $_POST['pass']=sha1($_POST['pass']); //Security.
                /* Update mysql tables here (preferably using AR) */
            }
            else //validation failed
                $disperrorous=true; //display errors
            $this->tulform->setValues(); //Auto refill form with posted values
        }
        else
        {
            $currentprofile=array('name'=>'John', 'website'=>'http://localhost/'); //Get your user's profile data here
            $this->tulform->setValues($currentprofile); //Fill form with values from the database
        }
        $this->viewdata['formString']=$this->tulform->formHTMLString('home/profile/formPoster', $disperrorous); //Get the HTML code of the form and put it in an array. first argument is the form's action, the second is a boolean (true=insert errors at the top of the form, false=do not. defaults to false)
        $this->load->view('home/profile', $this->viewdata); //Load view and give the HTML data

Because this weird forum system does not allow me to put more than 6000 characters in one message, I will post the library itself as a new comment in a few seconds.
#2

[eluser]Unknown[/eluser]
This library is hereby released under the New BSD license. See opensource.org for details. Contact me if you need more rights.

Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Tulform
{
    var $fields;
    var $validationFields;
    var $setValuesRan;
    
    function TulForm()
    {
        $this->CI =& get_instance();
        $this->CI->load->helper('form');
        $this->CI->load->library('validation');
        $this->setvaluesRan=false;
    }
    
    function setFields(&$fields=array())
    {
        $rules=array();
        $fieldStrings=array();
        foreach($fields as &$field)
        {
            $field['string']=array_key_exists('string', $field)?$field['string']:ucfirst($field['name']);
            $field['type']=array_key_exists('type', $field)?$field['type']:'text';
            $rules[$field['name']]=array_key_exists('validate',$field)?$field['validate']:"required";
            if($rules[$field['name']]=="notrequired")
                $rules[$field['name']]="";
            $fieldStrings[$field['name']]=$field['string'];
            if($field['type']=='text' || $field['type']=='password')
                $field['size']='40';
        }
        $this->fields=$fields;
        $this->CI->validation->set_rules($rules);
        $this->CI->validation->set_fields($fieldStrings);
        $this->CI->validation->set_error_delimiters('<div class="error">', '</div>');
    }
    
    function processPost() //after submitting form
    {
        $runresult=$this->CI->validation->run();
        
        if($runresult===false)
        {
            return $this->CI->validation->error_string;
        }
        return true;
    }
    
    function setValues($data=NULL) //no argument=get arguments from the validation lib
    {
        $this->setValuesRan=true;
        if($data===NULL) //get data from validation
        {
            foreach($this->fields as &$field)
            {
                if(!isset($field['value']) && $field['type']!='password')
                    $field['value']=$this->CI->validation->$field['name'];
                if($field['type']=='radio')
                {
                    if($this->CI->validation->$field['name']==$field['value'])
                        $field['checked']='checked';
                    elseif(isset($field['checked']))
                        unset($field['checked']);
                }
            }
        }
        else
        {
            foreach($data as $key=>$datum)
            {
                foreach($this->fields as &$field)
                    if($field['name']==$key && $field['type']!='password')
                        $field['value']=$datum;
            }
        }
    }
    
    function formHTMLString($posturl, $dispErrorString=false)
    {
        if(!$this->setValuesRan)
            $this->setValues();
        $htmlstring=''.form_open($posturl).'<table width="450px">';
        if($dispErrorString)
            $htmlstring.=$this->CI->validation->error_string;
        foreach($this->fields as $field)
        {
            if($field['type']!='submit')
                $htmlstring.='<tr><td>'.$field['string'].'</td><td>';
            else
                $htmlstring.='<tr><td>';
            unset($field['validate']);
            unset($field['string']);
            if($field['type']=='text')
                $htmlstring.=form_input($field);
            elseif($field['type']=='password')
                $htmlstring.=form_password($field);
            elseif($field['type']=='radio')
                $htmlstring.=form_radio($field);
            elseif($field['type']=='upload')
                $htmlstring.=form_upload($field);
            elseif($field['type']=='textarea')
                $htmlstring.=form_textarea($field);
            elseif($field['type']=='checkbox')
                $htmlstring.=form_checkbox($field);
            elseif($field['type']=='submit')
                $htmlstring.=form_submit($field);
            elseif($field['type']=='reset')
                $htmlstring.=form_reset($field);
            $htmlstring.='</td></tr>';
        }
        $htmlstring.='</table>'.form_close();
        return $htmlstring;
    }
}
?&gt;
#3

[eluser]Majd Taby[/eluser]
Hey tulcod, check out the form generation library that comes with CodeExtinguisher (I'd go and check the svn version at http://71.65.20.84:82/svn/codex/trunk ). It is extremely flexible, supports plugins, validation, callbacks, repopulation...everything. It also uses and array to define the form, like your library. When the new version of CodeExtinguisher comes out, I will be releasing the libraries I wrote for it as stand-alone libraries.




Theme © iAndrew 2016 - Forum software by © MyBB