Accessing the libraries/helpers

As mentioned earlier, the CI PHP view file can access any of the CI resources, such as calling the CI helpers, libraries, or models in the same way the controller does.

The following is a more elaborated and complete example of a PHP CI view file, accessing CI resources, such as libraries/models/helpers:

<HTML>
<?PHP
// URI is a built-in CI library
// if the rendering controller for this view was// http://mysite/myproject/mycontroller/test3
// the segment(1) = mycontroller – the controller name
// the segment(2) = test3 - the controller method
$the_controller = $this->uri->segment(1);
$the_method = $this->uri->segment(2);
?>
<H1>This View Rendered by Controller
<?=$the_controller; ?> </H1>
<H1>Using its method named <?=$the_method; ?></H1>

Forms

The CI PHP view file can contain any number of HTML data entry forms to accept the input data from the browsing user. We can use the CI form helper service to simplify the data entry buildup powered validation services.

The CI form helper provides a useful and comprehensive set of PHP functions for many data entry and input fashions. Among them we can find the data entry of the text field, the area text field, the radio button, checkbox, combo box, and menu option.

The following is a list of the most common CI form helper functions:

  • form_open()
  • form_input()
  • form_dropdown()
  • form_password()
  • form_upload()
  • form_textarea()
  • form_multiselect()
  • form_checkbox()
  • form_radio()
  • form_close()

The CI form helper generates an HTML portion that is rendered as part of the HTML file that is returned to the browser.

For example, let's take a look at a drop-down selection example of a color pickup.

<HTML>
<?PHP
$attr = ' class="nice_field" ';
$options = array();
$options[0] = 'Blue';
$options[1] = 'Green';
$options[2] = 'Yellow';
$default    = 1;
echo form_dropdown("color", $options, $default, $attr);
?>

The form_dropdown helper will generate the following code:

<select class="nice_field" name="color">
<option value="0»>Blue</option>
<option selected=»selected» value=»1»>Green</option>
<option value=»2»>Yellow</option>
</select>

For more information, refer to the CI form help user manual.

AJAX

Asynchronous JavaScript and XML services (AJAX) (http://en.wikipedia.org/wiki/Ajax) of JavaScript/jQuery integration within a view is critical today in almost any web application. It provides an advanced user experience by operating asynchronously in parallel to the user operations, and updates only certain HTML selector portions and not the entire page as anon AJAX updates operate.

AJAX has many use case examples to enhance the user experience. The following are few common usage examples:

  • Autocomplete while the user typing into a field all the matches found shown in a pop-up list for the user to choose. Without AJAX autocomplete the UI service is almost impossible.
  • When submitting a form data entry using AJAX enables to issue the server submission to store or process the date and show the result only in a specific selector (notification massage), instead of refreshing the whole page as form with the action, submission requires. (Format: Bullet)
  • When browsing many information pages (called pagination) and clicking on a certain page number to view. AJAX enables rendering the selected page to view within a selection DIV in the whole HTML page without refreshing the whole page. (Format: Bullet End)

Currently, AJAX is becoming an essential view component, mostly enabled via the popular jQuery library, which makes it easy to use. AJAX is an extremely valuable UI asset for building smart and interactive views. For example, the following is an example of the AJAX service that, for a given SSN (Social Security Number), provides the person's name and phone number in the defined selectors, if found, or alerts, if else. Whenever the user is clicking on the Get Info button, an AJAX call is triggered, and an asynchronous AJAX call to an AJAX controller is sent with the SSN to get the person's record. When the response is returned, if the SSN was found, the phone and name of the person will be updated. Otherwise, a notification will be provided that the SSN person's record was not found.

The following is the code implementing the process described previously, where the AJAX call is the heart of the operation:

<script type="text/javascript">
function get_person_info (SSN_val, name_sel, phone_sel, err_sel) {
  /*
  //SSN_val –the value of the SSN user typed in to search 
  //name_sel–the name input that the Ajax will update if SSN found
..//phone_sel-the phone selector to be update if SSN found as well
  //err_sel-the error message area, to explain error such as SSN //not found or some other error occurred.
  */
  varajax_url = '<?php echo base_url();?>ajax/get_person_info';
  $.ajax({
    type: "POST",    //Very important POST is the best
    url: ajax_url,
    // the URI of the AJAX server side controller method that will processes this request
    data: {SSN: SSN_val},
    // SSN is the parameter name
    // SSN_val is the value
    dataType: "json",
    //the retuned data expected to be JSON
    success: function(data) { 
      // the data is the array conversion of the JSON data// retuned to ease our usage in the JavaScript!
      if(data.result=='found') {
        // Let's show the name and phone of the person with the//given SSN
        $(name_sel).val(data.name);
        $(phone_sel).val(data.phone);
      } else{
        // SSN Not found in the database!
        // Let's notify SSN has no person match
        $(err_sel).css ('color', 'red'),
        $(err_sel).text('No person found with SSN' + SSN_val );
      }
    },
    error : //Ajax error occurred such as Ajax server not found//and so on
    function ( msg ) { alert ('Error:' + msg )
    $(err_sel).css ('color', 'red'),
    $(err_sel).text ('Error:' + msg);
  }
});
// Wait for the document to be ready and bind the user click// on the #get id selector to call the AJAX search service// with the user typed SSN
$(function(){
  $('#get').click( function(){ 
    get_person_info ($('#SSN').val(),
    '#name',
    '#Phone',
    '#err_sel'
  );
  });
});
</script>

The following is the portion of the HTML form itself:

<form>
<label>Enter SSN</label>
<input type='text' name="SSN" id="SSN">
<button id='get'>Get Info</button>
<BR/>
<label>Name</label><B id='name'></B><BR/>
<label>phone</label><B id='phone'></B>
</form>
<B id='err_sel'></B>

Parser configuration issues

The view is parsed by the CI parser before it is rendered back to the requesting browser. The default syntax to echo a PHP parameter / calculated expression value within the HTML tags is <?PHP echo trim($param); ?>.

However, CI provides automatic PHP short tag parsing support configuration at application/config/config.php and at the configuration parameter $config['rewrite_short_tags'] = TRUE;.

If rewrite_short_tags is set to TRUE, we can use the short tag of <?=trim($param)?>.

An important note on this is that in terms of debugging, the non-short/regular PHP echo format is preferred, as the short form errors might be more difficult to trace in this fashion. However, since this fashion is used in many code projects we've seen, we are mentioning it as well.

Integrating jQuery or other client-side libraries

CI provides the freedom to integrate any client-side libraries, so that CI does not have to be specially configured to, or we do not need to perform any special CI declarations.

The client-side integration is performed in the same fashion, as if no platform is being used; they are completely transparent. However, CI provides client-side jQuery code generation services via PHP, such as building the JavaScript library to create jQuery code, as part of the controller coding.

$this->load->library('javascript'),

However, for the latest jQuery and many other JavaScript-based solutions today, there's no need to use this fashion of rendered JavaScript portions, but we can use the JavaScript A-Z in the view itself instead. A great resource for the (wow level) JavaScript libraries can be found in the largest resource for the JavaScript libraries we've found so far at http://www.jsdb.io.

Many more cool links for client-side platforms can be found at https://delicious.com/eliorr1961.

Note that the directory path for the sources in the CI views is calculated, as if the view file is in the project root.

For example, let's say the JavaScript library is located at <Project_root>/javascript/myjs.js.

And the view is located either at the <Project_root>/application/views/view1.php or <Project_root>/application/views/topicB/view2.php view path under views.

After we provide the root path via the base tag using the built-in CI URL helper <base href="<?php echo base_url() ?>"/>, both will load myjs.js as follows:

<script type='text/javascript'src="javascript/myjs.js" ></script>

They load as if they were located at the project root. This is due to the fact that CI processes the requests and rendering views as part of the root directory index.php. Hence, all the directory paths for SRC or INCLUDE from view PHP portions are considered, as if they occurred from the project root directory. This is due to the fact that all URIs to the project are executed by index.php. So for all the project code, the directory path is as though your code was in the same directory of index.php or at the CI project root directory.

Plugins for rendering view

As mentioned at the beginning of this chapter, we can use third-party libraries to enable us to create more advanced rendering services in a template layout fashion.

For example, the CodeIgniter template class by Colin Williams available at http://www.williamsconcepts.com/ci/libraries/template/index.html.

This plugin enables us to define the rendered page as a Lego fashioned layout with predefined page regions, so that we can have a different PHP CI view to render each of them.

This way we can have great reusability and a unified look, and fill in the entire application page, which in many cases is a good UX (User Experience) practice. In this case, the user, let's say, will know that on the top they will have a certain main navigation area, on the right certain status info and operational shortcuts, and so on.

We can define one or more layouts, so that each page layout template will have its region's organization. Each region is commonly defined within a DIV.

Having several template layouts, we can initially choose the proper layout we want to use, and then we will load its region content using the CI views defined for each region. For example, let's say we want to have a certain layout named default.

The default template's main layout will be named, template, for example, using the view file main_template.php, so that main_template.php will include the following regions:

  • header
  • upper_navigation
  • content
  • footer

We shall perform the following configurations at application/config/template.php.

Note

This is not the CI built-in plugin, but an additional plugin with the library and configuration file, and other assets we have installed to our CI project.

//The default template shall be defined as follow:
//Note, more templates can be defined in the same fashion
$template['default']['template'] = 'main_template';
$template['default']['regions'] = array ('header', 'upper_navigation', 'content', 'footer'),

The main_template refers to application/views/main_template.php.

The content of main_template.php will include rendering of all the defined template regions as follows:

<html>
<body>
<div><?=$header;?></div>
<div ><?= $upper_navigation;?></div>
<div><!--main content area -->
<?= $content; ?>
</div>
<!-- #footer -->
<?=$footer;?>
</body>
</html>

In order to use the preceding template plugin, we will do the following:

First, load the template library in the CI controller constructor/s where we want to use the template. Remember that the template library is located at <Project_root>/application/libraries/Template.php.

We shall load the template library as follows:

$this->load->library('template'),

<Project_root>/application/libraries/Template.php

$this->load->library('template'),

Then, we will load the specific template file we have configured (we can define many to choose from), let's say, in the controller constructor, we will also assume that all the controller methods use the same template.

//set the selected template from the template config we want//to use
$this->template->set_template('default'),

Now, for rendering the template regions into a rendered view using the predefined view . We will do as follows:

For each template region at, let's say, <Project_root>/application/views/, we shall load it to the corresponding region as follows:

$this->template->write_view ('header', 'header_view', $data);.
$this->template->write_view('upper_navigation', 'upper_navigation_view', $data );
$this->template->write_view ('content', 'content_view', $data);
$this->template->write_view ('footer', 'footer_view', $data);

Now the template regions are rendered with their region view files. We can render the whole template with all its regions as follows:

// Now, we have all the regions rendered into the
// template instance buffer, we can render them all to
// the desired template base page.
$this->template->render();

The point to remember is that templates have great pros, but also some cons. The template dictates a very strict way of rendering a template base page that does not always have the desired flexibility, so that we may find ourselves writing several templates and switch between them, according to the UI situation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.222.185