[PHP] form tutorials in the codeigniter framework

Source: Internet
Author: User
Tags html header codeigniter

Codeigniter's form helper function: the input data sets us to focus on how you use your HTML pages.

One of the most important parts of any dynamic website is interacting with users, and this usually means using HTML forms.

The form helper function of codeigniter is a very useful piece of code.

It has a slightly different definition, making it easier to create a form. Create a form that allows us to input data in a browser. In the sites table of the websites database, we want to enter the website name, type, URL, and update date.

You can use simple HTML code to create a form,

Or you can create it in a controller, assign it to a variable, call the view, and send the variable to the view.

The following is the second method.

First, we must load the form helper function into the Controller that we need to use. Then, we put the following code into the Controller's constructor:

$this->load->helper('form');

Then, we must start writing the form. To generate input items of the form, we do not need to write the following:

$variable.='<inputtype="text"name="name"value="">';

CI allows you to do this:

$variable.=form_input('name',''');

(Remember that 'name' is the name of the input item, and 'value' is the content you want to enter. You can set the initial value here, or you can dynamically obtain the value from the form .)

Well, you may say that the 48 characters are 33 characters, not a few characters, especially the Helper function (the other 28 characters) That must be loaded first ). Why? The reasons are as follows:

1. One of the advantages of using form-assisted functions: The first advantage of using CI form-assisted functions is that your code is absolutely clear.

Chu. If you want a finer-grained input box, use HTML as follows:

$variable='<input type="text" name="url" id="url" value="www.mysite.com" maxlength="100" size="50" style="yellow"/>';

(Type is the type of the input box: Text, den, and so on. Name is the name of the variable to be obtained in the $ _ post array. The ID is set on the webpage
The identifier of the input box, if you use JavaScript. Value is the value displayed in the input box. It is a default value at the beginning.
You can enter a new value. Maxlength and size are obvious; style is a set of HTML formats or defined in CSS style sheet .)
CI replaces the preceding HTML code with an array:

$data=array('name' => 'url','id' => 'url','value' => 'www.mysite.com','maxlength' => '100','size' => '50','style' => 'yellow');$variable=form_input($data);

It looks pretty long. It is actually not longer than HTML code, and it is very clear, easy to understand and maintain. It is also dynamic.
The hidden form input box is very simple. If we want to automatically record the date when our database is updated. We put the date into a $ date variable, and then:

form_hidden('updated',$date);


If you want a 'text' input box to provide a place for your users to enter more than one line, you can use the form_textarea () function of CI. The following code uses the default length, A file input box is displayed on the webpage:

$data=array('name' =>'url','id' =>'url','value' =>'www.mysite.com');$variable=form_textarea($data);

CI form helper functions are particularly useful when you write drop-down boxes. If we want to change our URL input box to a drop-down box, users can select a URL from the drop-down list. First, store the options in the drop-down list into an array, and then call the form_dropdown () function:

$urlarray=array('1' =>'www.this.com','2' =>'www.that.com','3' =>'www.theother.com');$variable=form_dropdown('url',$urlarray,'1');

The first parameter in the URL drop-down box in the form to be passed is the name of the input box, the second is the array containing the drop-down list, and the third is the default option. In other words, if the user accepts the default value, your $ _ post array will contain the value 'url => 1', but your user will see the option 'www .this.com '.
If you use HTML code:

<select name="type"><option value="1" selected="selected">www.this.com</option><option value="2">www.that.com</option><option value="3">www.theother.com</option></select>

CI implementation code is actually relatively short and easy to learn.
If you store the directory of your selected URL in a database table ('urls'), it is easy to generate a dynamic drop-down box. First, read the data from the table into an array:

$urlarray = array();$this->db->select('id,url');$query=$this->db->get('urls');if($query->num_rows()>0){foreach($query->result() as $row){$urlarray[$row->id]=$row->url;}}

Repeat the previously used ciform_dropdown () function:

echoform_dropdown('type',$urlarray,'1');

Only $ urlarray's content changes; the Code is always the same.
If you are updating records in a table instead of inserting records, you do not want to display default values for your users. You want to display the existing value for that record. You should already know the id value of the record you want to modify. Therefore, you need to read the relevant records in the 'SITE' table in the database first. Are you sure you want to assign the query result to a variable, use the second variable to retrieve the relevant records of the first variable, and then call the form_dropdown function of Ci, pass the second variable and the corresponding column name as the parameter:

$this->db->select('id,url,name');$this->db->where('id','$id')$sitequery=$this->db->get('sites');$siterow=$sitequery->row();

Then, your CI drop-down box function will read the relevant information from it:

echoform_dropdown('url',$urlarray,$siterow->url);

There is not much space to discuss all form auxiliary functions. It can also write single quotes, hide file boxes, select multiple boxes, and some other input boxes. for complete information, see the CI user manual.

2. advantages of using form-assisted functions 2: Automation
The second advantage of using form-assisted functions is that they can automatically implement some functions. Otherwise, you can only write related scripts by yourself. First, it intercepts some characters of HTML, such as quotation marks entered by the user, and
Escape them to avoid breaking the form. Second, it is automatically linked. When you open a form, you must declare the target page, which will accept and process the form data. (In CI, This is a function in a controller rather than a static page. For example, it points to the Controller's update function .) Therefore, if you use pure HTML code, you will write as follows:

<form method="post"action="http:/www.mysite.com/index.php/websites/update"/>

If you use CI to open your form, you only need to do this:

form_open('websites/update');

CI automatically retrieves the basic URL in your Config File and locates the corresponding controller function. Once again, if you migrate your website, you only need to modify the config file instead of modifying the code file one by one. By the way, CI assumes that your form will always submit data in the form of post instead of get. CI generally uses the URL itself. Therefore, do not make a mistake.


The following is a simple analysis of a "display" model, that is, the model in MVC.
As a demonstration (slightly simplified), here is the display model:

<?phpclass Display extends CI_Model{/*create the array to pass to the views*/var $data=array();/*two other class variables*/var $base;var $status='';/*the constructor function: this calls the 'model' parent class *loads other CI libraries and helper sit requires,and dynamically setsvariables */function Display(){parent::CI_Model();$this->load->helper('form');$this->load->library('user_agent');$this->load->library('errors');$this->load->library('menu');$this->load->library('session');/*now set the standard parts of the array*/$this->data['css']=$this->config->item('css');$this->data['base']=$this->config->item('base_url');$this->base =$this->config->item('base_url');$this->data['myrobots']='<metaname="robots"content="noindex,nofollow"/>';/*note that CI's session stuff doesn't automatically recall the extra variables you have added, so you have to look up the user's status inthe ci_session stable*/$sessionid=$this->session->userdata('session_id');$this->db->select('status');$this->db->where('session_id',$sessionid);$query=$this->db->get('ci_sessions');if($query->num_rows()>0){$row=$query->row();$this->status=$row->status;}}/*function to assemble a standard page. *Any controller can call this. *Just supply as $mydata an array,of key/value pairs for the contents you want the view*to display.  *Available variables in this view are:mytitle.menu,mytext,diagnostic */function mainpage($mydata){$this->data['mytitle']='Monitoringwebsite';$this->data['diagnostic']=$diagnostic;foreach($mydataas$key=>$variable){$this->data[$key]=$variable;}/*here's the menu class*/$fred=newmenu;$this->load->library('session');$mysess=$this->session->userdata('session_id');if(isset($this->status)&&$this->status>0){$this->data['menu']=$fred->show_menu($this->status);}$this->load->view('basic_view',$this->data);}}?>

Use the following code to call this homepage in any controller:

$this->load->model('display');$this->display->mainpage($data);

The view is being dynamically assembled to fully meet the needs.


Let's take a look at the CI verification class.

An important task when writing HTML forms is to check the input. We all know we should do this,... Until now, we have written a simple form that will trust any data input by any user. You should realize that some users may be unfriendly, and all others are irresponsible. (Don't Tell them directly .) If they make a simple mistake, they will. Make sure that you always check user input data and make them meet your requirements. You can do this with JavaScript on the client side, but it does not have much to do, so users can easily bypass it. The check on the server requires an additional information back and forth, which is worth the extra cost. Writing verification code is also quite complicated, but you must have guessed it. CI provides a verification class to make this work very easy. Let's change our form processing process to implement verification. You need to make some adjustments in the form, and make some adjustments in the function it points. If your form starts with form_open ('sites/Update'), you need to modify the 'update' function in the 'sites 'controller. If you do not use the form helper function of Ci, the equivalent HTML code is:

<form method="post" action="http:/www.mysite.com/index.php/sites/update"/>

Next, we need to do three things: 1. Set verification. 2. Set the controller. 3. Set the form.

1. Set verification rules

Load the verification class in the function specified in your form and declare your validation rules:

$this->load->library('validation');$rules['url'] ="required";$rules['name'] ="required";$this->validation->set_rules($rules);


The 'url' and 'name' input boxes must contain the input content. CI provides various operations to ensure that some operations are performed. The user manual fully explains these operations.
Their meaning is very clear: min_length [6] obviously means that the length of the input information must be greater than or equal to six characters. Numeric means that only numbers can be entered, and so on.
You can also combine rules and connect them with "|:

$rules['name']="required|alpha|max_length[12]";

It indicates that it cannot be blank, with a letter and a length of at least 12 characters. You can even write your own rules.


2. Set the Controller
Still in the same function, create a 'if/else' statement:

if($this->validation->run()==FALSE){$this->load->view('myform');}else{$this->load->view('success');}

You confirm the test, and if the input content cannot pass the test, return to the input page. (If you generate your view in a function in a controller, use $ this-> myfunction instead of $ this-> load-> View ('myform ').

If the verification is successful, view ("success") is generated to inform the user that the entered information has been accepted, and then a link is provided to let him go to the next step.


3. Set the form

The input information form must also be adjusted accordingly. If the verification fails, you must not only have the system return to the input interface, but also specify the error and the cause of the error. Therefore, you must provide an additional information somewhere in the form:

$this->validation->error_string;

This line of code displays the appropriate information to prevent the user from hacking. You also need to automatically enter the content that the user has entered correctly. Otherwise, the user must enter the information that they have entered correctly again.
First, you need to add more code to the Controller. In addition, it is immediately added after the validation rules, and an array is added to store the user's prompt information. The key name of the array is the name of the input box in your form, and the value is the error message:
-22-$ fields ['url'] = 'theurlofyoursite ';
Then, add a line of code:

$this->validation->set_fields($fields);

Now you have declared an array of information in the Controller. You only need to add the code to display the information in the form. For HTML code, this will be:

<input type="text" name="url" value="<?php echo $this->validation->url; ?>"/>

Or, if you are using the form helper function of CI:

$variable.=form_input('url',$this->validation->url);


If you use this form to insert a new record to the database table, the above Code is enough. If you are using a form to update a record that has already been input, when the form is displayed for the first time, the actual information in the database table should be displayed in the input box. At this time, its value should be read from the database (remember the previous example of calling $ siterow-> URL ?) When you update an existing record, the last input content cannot pass verification because the content of an input box is not entered. Before you return to the form, you need to enter the information you just entered in the input box that passes the verification, and re-enter the information read from the database table in the input box that fails the verification. Otherwise, you need to enter the information that has been verified again.
Fortunately, this can be achieved through a simple "If/else" statement:

if(isset($_POST['url'])){$myvalue=$this->validation->url;}else{$myvalue=$siterow->url;}

When the form is displayed for the first time, there will be no content in the $ _ post array. Therefore, you can read information from the relevant table of the database. But after you submit it once, the $ _ post array contains data, So you choose the value returned by the validation function. Read the CI User Manual to learn more about form verification. You can also prepare your data automatically. For example, you can use it to eliminate possible cross-site scripting attacks.
Compile your own complex verification standards. For example, the user-entered values cannot already exist in the database to compile your own error information. The CI verification class is very useful and powerful, it is worth the time to study and
Master.


Summary:
We have learned how to generate a view in Ci and how to create a "mini-View". You can nest the view into other views. This means that you can create a shared HTML header and HTML tail to reuse the view. We have also seen how CI helps you compile HTML input forms and simplify HTML form writing through forms auxiliary functions. Finally, we learned the CI verification class, which is used to check user input information.
Useful tools. Nothing is perfect, but this tool can block your user input garbage or attempt to attack. It also makes your website look more professional and can effectively capture various input errors caused by users, rather than simply accepting meaningless input.
Throughout the learning process, we once again tried the MVC principles and sometimes made some changes to make life easier. CI has a very flexible philosophy: To solve problems efficiently, you must learn to use tools flexibly.

Next we will compare the code in Ci with the final result generated.

/* The following are some simple elements of Form submission */ECHO form_input ('name', 'name _ value'); // insert a text box. Equivalent to: // <input type = "text" name = "name" value = "name_value"/> $ DATA = array ('name' => 'url ', 'id' => 'url', 'value' => 'www .mysite.com ', 'maxlength' => '20140901', 'SIZE' => '50 ', 'style' => 'yellow'); echo form_input ($ data); // deploy the form information using arrays. It is equivalent: // <input type = "text" name = "url" value = "www.mysite.com" id = "url" maxlength = "100" size = "50" style = "yellow "/> echo form_hidden ('updated ', 'date is 2013/02/08 '); // hide the data. Equivalent to: // <input type = "hidden" name = "updated" value = "date is 2013/02/08"/> $ DATA = array ('name' => 'url ', 'id' => 'url', 'value' => 'www .mysite.com '); echo form_textarea ($ data); // set the text area. Equivalent to // <textarea name = "url" Cols = "40" rows = "10" id = "url"> www.mysite.com </textarea> $ urlarray = array ('1' => 'www .this.com ', '2' => 'www .that.com ', '3' => 'www .theother.com'); echo form_dropdown ('url', $ urlarray, '1 '); // set the drop-down menu. Equivalent to // <select name = "url"> // <option value = "1" selected = "selected"> www.this.com </option> // <option value = "2 "> www.that.com </option> // <option value =" 3 "> www.theother.com </option> // </SELECT>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.