Blog Archive

Showing posts with label FUEL CMS. Show all posts
Showing posts with label FUEL CMS. Show all posts

Wednesday, 19 February 2014

Creating an authentication system for Fuel CMS using the Ion Auth library and Codeigniter hooks

Fuel CMS has an excellent system for publishing pages to a website. But what if you wanted some of those pages to be "members only", protected on the front end by an authentication layer? There is no in-built method to do this, but there are plenty of ways in the underlying Codeigniter framework to enable it.

In this tutorial we will install and use the excellent Ion Auth library written for Codeigniter by Ben Edmunds to create just such an authentication layer for Fuel CMS pages.

The Ion Auth library is available as a zip from GitHub, and is already packaged in the Codeigniter directory hierarchy, so just unpack it into your Fuel CMS directory, in the /application/ folder, and run the SQL provided. We will be making use of it just as if it were running in a plain vanilla CI site.

Preparing Fuel CMS for front end authentication

From Fuel’s CMS perspective, we are going to alter the default layout (“main”) for “pages”, but we want to set Fuel’s page mode to “auto” for our purposes, so change $config['fuel_mode'] (in /application/config/MY_fuel.php) if it is set to anything else.

A bit of background on the way Fuel CMS stores "pages" might be useful to understand the concept of "layouts".

"Pages" are stored in 2 database tables in Fuel:
  1. Fuel_pages is a relatively small table which stores the id, location (uri), published status, cache mode and related author and timestamp data. This is the “parent” table.
  2. Fuel_page_variables (the “child” table) stores the actual content of the page, related by a foreign key to Fuel_pages. What makes the Pages module in Fuel so flexible is that the "layout" fields are stored as name and value pairs, which means they are easily extendable. More fields = more rows in this table.
So the HTML input fields that are evident in the Pages module of the Fuel admin system are actually configured by "layouts", which are really just PHP arrays. These array templates are then stored, in name value pairs in the Fuel _pages_variables table. Importantly, each pair is also classified by a "type", so an input field might be text, multi, date, file and so on (more info here). This means if you want to add to the fields/inputs for a page layout, you don't need to alter the SQL structure of the storage table, you just add to the PHP arrays! This is a HUGE timesaver!

If you need to have different content layouts in your site (eg your "Home" page has need of video urls, or your"About" page differs from other pages as it has formatted staff biographies) then one way to tackle these content differences is by making use of one or more layouts. The choice of layout is actually there in the page (Fuel_pages) definition. Try swapping between "main" and "alias" layouts in the pages module and see how the field layout alters completely!

To change or create new layouts, we need to edit MY_fuel_layouts.php (found in the /application/config folder). Note that if you add another layout to the MY_fuel_layouts file, then you should also provide a new layout view file in /application/views/_layouts of the same name as the config index..

However, we are going to keep things relatively simple here and just alter the "main" layout. We want simple “boolean” authentication across all the pages we create, and for the sake of this tutorial we will stick with one layout that incorporates this. So find the array definition $config['layouts']['main'] and add to the end of the "fields" sub-array this:

'auth' => array(
'type' => 'enum',
'options' => array('0' => 'No', '1' => 'Yes'))


Here we are adding a field called "auth" to the main layout. It's an enum type, so Fuel's Form Builder Class will render a radio button array (as there are only 2 values) and the values will be 0 and 1, with labels "No" and "Yes" respectively.
admin_auth_field

Save MY_fuel_layouts.php and call up the pages module in the Fuel admin to see the result. Note that because we added the value  after the Body fieldset definition, the new field "auth" will appear last under the "Body" tab in the "Layout Variables" section of the page. Select “Yes” for the new field. Now when you save the page, the selected value (1) will be stored in the Fuel_page_variables table. Try running the following SQL in your database client to verify the saved value (your page_id value may differ):

select * from fuel_page_variables where page_id = 2 and name = 'auth';

The result may look something like:

page_variable_auth_sql


Note that if you re-save that page, but with “No” selected, you will observe from running the SQL query again that the “No” value (0) is actually saved as an empty value.

Ok, so we can now flag which pages are to be protected. But how to actually check the value in the page against Ion Auth?

Using Codeigniter’s hooks

There are a few ways to implement Ion Auth in Codeigniter – we could use the controller system to create an authentication controller, and extend from that when we need to employ login credential checks. But for this tutorial we will use Codeigniter’s Hooks.

As the name implies, Hooks are means of intercepting processes in Codeigniter at crucial points. With our authentication system, we want to check at the Controller level, or very near it. One hook “post_controller_constructor” suits our requirements. It will be almost as good as writing the Ion Auth authentication into each and every controller’s constructor method. Note that doing this may introduce performance penalties as it will be run on every controller call in the application, so it is important to tread lightly using this technique!

To create a Hook, we need to add an entry to /application/config/hooks.php:

include(FUEL_PATH . 'config/fuel_hooks.php');
 
/* Our hook code for Ion Auth */
$hook['post_controller_constructor'][] = array(
    'class' => 'Auth_hooks',
    'function' => 'cms_auth',
    'filename' => 'Auth_hooks.php',
    'filepath' => 'hooks',
    'params' => array(),
    'module' => 'app',
);

Note that we add this hook definition after the include for Fuel’s own hooks, and that we employ the “multiple calls to the same hook” extra array index (this is because Fuel is already using this Hook point, so we are adding to it with the extra array dimension).

So we need to have a class called Auth_hooks.php in /application/hooks, with a method “cms_auth()”. We don’t have to use a class, but we will!

class Auth_hooks {

    function cms_auth() {
        $CI = &get_instance();
        $redirect_to = 'auth/login';
        $pagevars = $CI->fuel->pagevars->retrieve(uri_path());
        if(isset($pagevars)) {
            if(isset($pagevars['auth'])) {
                $CI->load->library('ion_auth');
                if(!$CI->ion_auth->logged_in() && $pagevars['auth'] == 1) {
                        redirect($redirect_to);
                }
            }
        }
    }
}


This is a very simple means of protecting CMS content using hooks. If the page is set to require authentication ($pagevars['auth'] == 1) and Ion_Auth detects no login credentials, then we redirect the user to the auth/login controller (which should have been added when the Ion Auth zip was unpacked). Note that we use the Pagevars class to find any variables for the given url. One other important note: turn off caching for authenticated pages - otherwise you may inadvertently store login information.

There are a number of improvements we could make to this basic authentication handling. For example, we could make it more fine grained and authenticate against Ion Auth’s groups (ie a user must be logged in and a member of group or groups x,y,z…). We could make the redirect a bit more helpful, such that after logging in the user is redirected to the original page he or she was rejected from.

All of this is possible and may be the subject of a further post!

Wednesday, 1 May 2013

Putting the Form Builder class to work in FUEL CMS

Building forms in HTML is rarely a pleasure, so any functionality that aids that chore is a boon. Codeigniter has some form helper functions that are handy, and separately, the Validation class to prepare form data for processing. FUEL CMS builds on these to create the seriously useful Form Builder class.

In this tutorial I will show how useful it can be by building a form with CAPTCHA capabilities, and error responses.  I will be using v1.0 of FUEL CMS. I will use the CAPTCHA library found here CodeIgniter-Captcha

The form

 The source fields for the Form Builder class can be stored as an array, so why not create a config file for forms? In the application/config folder, create a file imaginatively called "forms.php". This can store one or more forms, and in this example it will have a "contact us" type form like so:


/* 
* CONTACT FORM
 */
$config['contact']['form'] = array(
  'required_text' => '* required fields',
  'css_class' => 'regular',
  'form_attrs' => array('method' => 'post'),
  'submit_value' => 'Send'
);

/* Setup fields */
$config['contact']['fields'] = array(
  'name' => array('type' => 'text', 'label' => 'Your name', 'required' => TRUE),
  'email' => array('type' => 'text', 'label' => 'Your email', 'required' => TRUE),
  'telephone' => array('label' => 'Your telephone'),
  'enquiry' => array('type' => 'textarea', 'label' => 'Your enquiry', 'required' => TRUE) 
);


The configuration for Form Builder is in 2 parts - the form itself, and then the fields. The keys for the fields are self explanatory, the form configuration keys are more complex - some are attributes, others are HTML snippets.

How do we put these to work in Form Builder? We will need to load the config file in our controller, and supply the "form" array as the configuration parameters to the class. So in a controller we can do:

class Contact extends CI_Controller {
    
  public $form_data;

  public function __construct() 
  {
    parent::__construct();
    // load contact config
   $this->load->config('forms');
   $this->form_data = $this->config->item('contact');
  }
...


For convenience I am putting the loaded "contact" array into a public variable. Later in the controller, Form Builder can be configured like so:

$this->load->library('form_builder', $this->form_data['form']);
$this->load->library('captcha');
$this->load->library('form_validation');


This configuration can occur in a method of your choosing - since this will be for an index page, my code was in the index() method. Note also I am loading the CAPTCHA library referred to above, and the form validation library.

As per the typical Codeigniter form validation, this same controller method should use some validation rules:

/* validators */
$this->form_validation->set_rules('name', 'Name', 'trim|required|max_length[128]|xss_clean');   
$this->form_validation->set_rules('email', 'Email', 'trim|required|max_length[256]|valid_email|xss_clean');
$this->form_validation->set_rules('telephone', 'Telephone', 'trim|max_length[24]|xss_clean');   
$this->form_validation->set_rules('enquiry', 'Enquiry', 'trim|min_length[8]|max_length[1024]|xss_clean');

// captcha rule - use codeigniter validation callback feature! NB we set function beginning with
// underscore so it won't get actioned by URL request - hence double underscore in callback 
// (callback convention + controller method convention)!
$this->form_validation->set_rules('captcha', 'CAPTCHA', 'required|callback__captcha_check');
$this->form_validation->set_message('_captcha_check', 'Text did not match the characters in the image');


The validations for the fields loaded by the forms.php config file are unremarkable, but something special is happening regarding the CAPTCHA input field - another method is being called (_captcha_check) within the rules argument. The method call is prefixed with "callback_" which is Codeigniter's way of implementing a function call for callbacks. So there will need to be another method in the controller like:

// CAPTCHA callback function - used by validation 
function _captcha_check($str)
{
  if($this->captcha->check($str))
     return TRUE;     
  else 
    return FALSE;   
}


The method follows the Codeigniter convention of beginning with an underscore so that it is not available as a URI request. The callback gets the string from the supplied input and uses the Captcha library to test if it matches the session string. A boolean return completes the validation.

So far, nothing has happened about the tiresome form construction! Here's how it will happen: we only need show the form either on initial load, or if the form has been submitted and failed validation, so inside of the validation test for "no validation"

if($this->form_validation->run() == FALSE) {

  // create CAPTCHA img and field
  if($this->captcha->create()){
    $captcha = $this->captcha->html_data;
  } else {
    $captcha = 'Captcha : ' . $this->captcha->debug;
  }
  // append captcha html to text field of same name
  $captcha_html = "<p title='Input the characters in this image in the field below'>";
  $captcha_html .= img($captcha) ."</p>";
  $this->form_data['fields']['captcha']['before_html'] = $captcha_html;
    
  // See if submit has occurred (and failed) & populate fields
  // with submitted data, and append error too.
  if($this->input->post('Send'))
  {
    foreach($this->form_data['fields'] as $key => $val)
    {
      $this->form_data['fields'][$key]['value'] = $this->input->post($key);
      $this->form_data['fields'][$key]['after_html'] = form_error($key);
    }
  }
  $data['form'] = $this->form_builder->render_divs($this->form_data['fields']);
}



This is where Form Builder really comes into its own. Remember that earlier we created a class property array $this->form_data? The last line in the code snippet above builds the entire form from the config file array "fields" using this property. Using the class method render_divs(), it constructs the form using div tags to separate the label / input rows! That's it! Providing your CSS is up to snuff, the form should look fine already.

But what else is going on here? Two things: a CAPTCHA image is created using the library we referenced earlier, and inserted into an HTML sandwich, which is pre-pended to the CAPTCHA field. What CAPTCHA field?? We've been sneaky here and made a form field ("captcha") on the fly - and then been doubly sneaky by bolting it on with Form Builder's 'before_html' key so that the image appears above the text input field that will be validated by the rules we set earlier.

But wait, there's more! We then loop over the fields from the config array 'fields' index, and append any form errors using the key 'after_html', whilst also adding the submitted value back into the correct input's 'value' attribute. Double whammy!

And that is all contained in $data['form'], which is going to be part of the array we send to the view in Codeigniter fashion like so:

// use Fuel_page to render so it will grab all opt-in variables and do any necessary parsing  
$this->fuel->pages->render($view, $data);   


This view rendering is part of FUEL CMS' Pages class, but it's the same principle as if we used the Codeigniter load->view('view', $data) arrangement.

Thus all we need do in the view itself is echo out the form with:

<?php echo $form; ?>


So we should have:
  1. A nicely constructed form
  2. A captcha image and input field within it
  3. A form that validates itself, and reports errors and displays the submitted values


Wash, rinse, repeat.

Thursday, 7 February 2013

The ins and outs of inline editing in FUEL CMS

FUEL CMS automatically allows inline editing of CMS content from the front end of a site. If you are logged in as an administrator,a tool bar will appear on the front end allowing you to edit content such as page titles, meta descriptions and body content there and then, thus making a trip to the admin redundant. Content is made editable via modal dialogue forms. The editable fields are defined in application/config/MY_fuel_layouts.php and the array key defining a layout should match a view file in views/_layouts.

Controllers and CMS content


It is of course possible to create controllers and views that also mix in CMS content - just fetch the CMS fields for a given url and combine the controller content (whatever that might be - from a model, or variables) and make sure the view can show both.

For example a (v1.0) controller like the following:

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

class Rendercms extends CI_Controller {
  
    public function __construct() {
        parent::__construct();
    }
  
    public function index()
    {
        $params;
        $view = 'rendercms/index';
        $vars = array();
        $cms_vars = array();      
        $vars['some_controller_content'] = "Me? I'm controller content!";
        $cms_vars = $this->fuel->pagevars->retrieve($this->uri->uri_string());
        $all_vars = array_merge($cms_vars, $vars);
      
        if($this->input->get('cms') == 'true') {
            $params = array('render_mode' => 'cms');      
        }

        $this->fuel->pages->render($view, $all_vars, $params);  
    }

}

 
combined with a view file (views/rendercms/index.php) such as:

<?php echo fuel_var('body', 'No CMS content here, sorry'); ?>
<hr>
<?php echo $some_controller_content; ?>
<hr>
<?php echo $some_variables_content; ?> 

<hr> 
<p>And I'm humble view HTML</p>
 
can demonstrate the features of FUEL CMS's abilities. The view file will show any CMS content at the url /rendercms (or simply default to 'No CMS content here...'), it can also show the 'some_controller_content' created by the controller, and, as a bonus, it picks up a variable defined in views/_variables/rendercms.php:

<?php

$vars['some_variables_content'] = "I'm only variable content";

?>


So far so good! However, notice the FUEL toolbar on this page (you need to be logged in to the admin, remember, to see this). It's there, but there is nothing it can do to edit the CMS content! Those features, the "toggle editable areas" and "toggle page's publish status" and the rest, are unavailable.

Depending on your needs, this may be only a mild inconvenience. But is there a way round it - a way to get everything!?

The answer is yes, but with some drawbacks.

Everything


In the controller above, you will notice I added a conditional to check for a parameter "cms=true".

Add that parameter to the url (/rendercms?cms=true) and refresh the page (NB make sure in config.php you have allowed GET: $config['allow_get_array']  = TRUE;).

Now only the CMS content is visible, in whatever layout file the CMS has defined (probably 'main' if nothing else). The variables and controller content and even the view file itself are now ignored because the render_mode => 'cms' specification (the default value is 'views'). The 'main' layout file alone is being used, and that, of course, lacks your custom controller content!

So, if there was a layout file that could echo the controller, variable AND CMS content, we'd win!

Make a file ("rendercms.php") in the views/_layouts folder that includes all these variable placeholders eg:

<html>
<head><title><?php echo fuel_var('page_title'); ?></title></head>
<body style="font-family: Georgia;">
<h1>This is a layout file</h1>
<?php echo fuel_var('body', 'No CMS content here, sorry'); ?>
<hr>
<?php echo $some_controller_content; ?>
<hr>
<?php echo $some_variables_content; ?>
</body>
</html>


Now go back to your CMS page in the admin, for "rendercms". In the layout field (you may need to refresh the admin page to reload the options) you should see "rendercms" as a layout. Select it, and save the page. Now when you return and refresh /rendercms?cms=true you should see CMS fields that are editable from the toolbar, controller content and variables content combined.

The additional drawback to this solution, however, is that to make the 'layout variables' fields appear in the admin, you will also need to add an array for "rendercms" in MY_fuel_layouts.php. eg:

$config['layouts']['rendercms'] = $config['layouts']['main'];

Here for example, we copy all the fields for the 'main' layout to the new 'rendercms' layout.

So to make a consistent inline editing experience for the user, where you have CMS & controller content combined, you need to

  1. make a layout file and 
  2. a layout configuration array to support it, in addition to 
  3. the controller, 
  4. view 
  5. (and optionally) the variables file.

It's conceivable though, that you could make just one layout file, and make it contain all the possible controller content it might need to accommodate, eg by adjusting its own layout according to which (controller) url it is responding too. Conceivable, but possibly monstrous! The viability of that solution would depend on the scale, complexity and number of your controllers.

If however inline editing isn't such a priority, the original method outlined above is pretty simple to effect. If you want, that functionality can be moved to MY_Controller, and controllers that combine CMS and their own content can be extended from that.

Thursday, 24 January 2013

Adding autocomplete to a simple module field in FUEL CMS

This quick tip follows on from Add a JQuery plugin to FUEL CMS module admin page.

FUEL CMS v1.0 uses JQuery's UI library  in the admin by default. This means features like auto-complete, or auto-suggest if you prefer, are very easy to add to simple modules.

In your model, add the form_fields() function if it is not already present, and choose the field in the model you wish to add autocomplete to - in this example, I'm going to suggest emails in an email field called "contact_email":

$fields['contact_email'] = array(
    'class' => 'email_suggest', 
    'comment' => 'Known emails will be suggested as you type'
); 
 
The array configuration here is minimal, we are just attaching a CSS class to the field, and adding a comment so that hovering over the label in the form will show the comment as a tooltip. More field options are shown on this page.

Since suggesting emails to the user when filling in an email field is so useful, I want to do it for any module that has an appropriate field, so instead of adding the JQuery function to the model's Controller.js, I'm going to add it to the parent class, BaseFuelController.js, then it will be available to call from any extended class.

Find a suitable location in BaseFuelController.js to put the following (I put it at the very end, don't forget to extend the array by putting a comma before it)

email_suggest : function() { 
    $('.email_suggest').autocomplete({ 
         source: '/suggest_emails' 
    });
}
 
As per the Autocomplete documentation, this function (email_suggest) will apply the autocomplete to an element with a class of "email_suggest", and will look for data remotely in the url '/suggest_emails'.

I made a controller to return emails in a JSON array from that url, but you could use the opt-in view functionality of FUEL CMS and create a view file of the same name, thus saving a bit of typing! If the emails are private, you might want to protect them from being viewed by just anybody (ie outside of the admin). You could opt to put the url inside of the Fuel module, but that's another project.

In the Controller.js of your module (mine was an "events" module, so it was named EventsController.js), you then just need to add something like this:

add_edit: function(){
    this._super(); 
    this.email_suggest(); 
} 
 
Since the module's Controller.js is an extension of the BaseFuelController.js, the function is called from the parent class. So for other modules that need the same feature, just add this.email_suggest(); to the add_edit() function in their Controller.js, not forgetting to define the js_controller key in MY_fuel_modules for each module you need to.

And that's pretty much it!

Thursday, 8 November 2012

Creating an advanced module in FUEL CMS v1

Creating an advanced module in FUEL CMS v1 (beta) has become rather easier, since this release provides some “scaffolding” from the PHP CLI which creates the core files you will need to begin your project.

If it’s not clear what an “advanced module” is, it is a mini application folder under the fuel/modules path. If you never intend to repeat the simple modules you create as per Codeigniter, then you might not find the extra effort worthwhile. If you have a mind to portability, or just like tidy modularity, then trying an advanced module is time well spent.

For this tutorial, I’m going to take a well known library from Codeigniter, and ease it into a FUEL CMS advanced module. The library is Ion Auth, an authentication application that creates a secure login with the further ability to associate logins with groups. I’m going to use that library’s users table as my “members” table, but keep groups more or less the same.

Step one

The first task is to decide what to name the module. This is important, as you will not want any clashes with sub controller names, which will cause grief later on. I chose “membership”, which means that using the Ion Auth controller methods, urls will look like “your-site/membership/login”, “your-site/membership/logout” and so on.

STEP TWO

Having decided on a name, it’s time to generate the scaffold files. You will need to use the command line, so navigate to your installation and issue a command like:

php index.php fuel/generate/advanced/ membership

This will create a folder under the fuel/modules path called “membership”, and populate it with config, controller and helper files, and much else. But, it won’t create models, as these are much more likely to be unique to any given project. So the next CLI command will create the models

php index.php fuel/generate/simple members:groups membership

That command deserves some explanation: although the path includes “simple”, the arguments, the last especially, instruct the creation of models “members” and  “groups” in the “membership” advanced module folder. It is possible to chain more model names together using a semicolon as a separator, if you need to. The database tables “members” and “groups” also get created (provided you have set up a database connection already), but only in a rudimentary fashion.

So, after that you should have a “members_model.php” and “groups_model.php” in the modules /models subfolder.The models are quite basic, but functional. They can be made more sophisticated, as per the tutorial here.

Step tHREE

Next we will configure the module to play nicely in FUEL’s admin.

The previous CLI commands will have added the “membership” module to the FUEL CMS admin for you, with a link to an admin url “membership”. If you follow this link, it will be horribly broken. That’s to be expected. The admin doesn’t know what to do with “/membership”. Open the module’s routes file (membership_routes.php) and add this:

   1:  $route[FUEL_ROUTE.'membership'] = 'membership';
   2:   
   3:  $membership_controllers = array('members', 'groups');
   4:   
   5:  foreach($membership_controllers as $c)
   6:  {
   7:    $route[FUEL_ROUTE.$route[FUEL_ROUTE.'membership'].'/'.$c] = FUEL_FOLDER.'/module';
   8:    $route[FUEL_ROUTE.$route[FUEL_ROUTE.'membership'].'/'.$c.'/(.*)'] = FUEL_FOLDER.'/module/$1';
   9:  }



This is going to map 2 new links we will be creating, “members” and “groups”, on to FUEL’s Module controller class. Doing that will hook into the CRUD facilities of the admin. Note that we don’t need to actually create controllers for “members” and “groups”,  we are just mapping routes on to a class that is itself a controller, and will do all the admin stuff for us.


STEP FOUR


To create the links we need to edit the module’s config file (config.php)


   1:  $config['nav']['membership'] = array(
   2:    'membership/members' => 'Members',
   3:    'membership/groups' => 'Groups'
   4:  );
   5:  // tables for membership
   6:  $config['tables']['members'] = 'members';
   7:  $config['tables']['groups'] = 'groups';



Now when we follow these new links in the admin, there is a new error: “unable to locate the file…”. The model’s are missing! This is because we need to do some more configuring, this time in “membership_fuel_modules.php”. We need to specify where the models are:


   1:  $config['modules']['members'] = array(
   2:    'model_location' => 'membership',
   3:    'module_name' => 'Members',
   4:    'module_uri' => 'membership/members',
   5:    'model_name' => 'members_model',
   6:    'nav_selected' => 'membership/members',
   7:  );
   8:  $config['modules']['groups'] = array(
   9:    'model_location' => 'membership',
  10:    'module_name' => 'Member Groups',
  11:    'module_uri' => 'membership/groups',
  12:    'model_name' => 'groups_model',
  13:    'nav_selected' => 'membership/groups',
  14:  );



Actually, we do a lot more here than specify the model location, but it’s all pretty obvious.


At this point you should be able to use the admin navigation links (members, groups) and see list & create pages served up by FUEL’s Module class. Sweet.


STEP FIVE


Return to your SQL editor! Although the scaffold process created database tables, they need to be more specific. For the “members” table I repurposed the “users” table from the Ion Auth library. Likewise, the “groups” table is the same as the one in that package.


STEP SIX


The last step requires adding and configuring the Ion Auth library. The files simply go in the module’s folder, just as they would if they were in the application directory.


I repurposed the scaffolded membership controller to be the equivalent of the auth controller supplied with the library. Note however that the generated class is intended to be an admin compatible one, based on Module. For a front-end facing controller, we can just use CI_Controller, MY_Controller or whatever. It’s also important to note that some of the loading methods need altering: eg instead of regular

$this->load->library('ion_auth');



we need to use the one specifically for modules:

$this->load->module_library('membership', 'ion_auth');



which explicitly tells FUEL what module to look in (eg membership/libraries in this instance).


There are various paths that need to be edited from the original Ion Auth code: the controller path “auth” is used as a target for redirect() quite often, and the views all use “auth” in their actions. We can make use of a constant found in “membership_constants.php”, and substitute MEMBERSHIP_FOLDER. Of course if you elected to call you module “auth” in the first place, there would be no need.


The Ion Auth library has its own config file, and we can assign the tables variables to the database names we are using  eg

$config['tables']['users'] = 'members';



By visiting /membership/login from the front end, we should now see the Ion Auth views, and a functioning authentication system.


AFTERWORD


Although most aspects of this demonstration are working, there are lots of holes. Ion Auth uses some crafty hashing to create its passwords, so although you can create users from /membership/create_user (if you are logged in as the ion Auth admin) you will not create them properly from the FUEL admin. This is because the hashing process is not hooked in to the members_model.


Additionally there are other fields on display by default that should either be hidden, or be a different type.


Also, the groups table isn’t even used by the members model! However, v1 of FUEL CMS introduces an ingenious “has_many” relationship, and it is possible to add a multi-select field to the members_model so that group associations can be stored in the fuel_relationships table, without fiddling around with separate lookups.


These deficiencies are rectifiable though, and I will leave these to the reader to solve.

Friday, 24 August 2012

Advanced modules with simple module admin in FUEL CMS

I’ve been tempted lately to turn some of the simple FUEL CMS modules I’ve created into “advanced” modules. Partly I’ve wanted to do this to improve my understanding of Fuel, and partly because the concept of advanced modules make a lot of sense from a modularity and re-use point of view. Advanced modules are mini-applications, with their own contained controllers, models, views and assets. By copying their root folder, you have the entire file-set, rather than having to rummage in the applications directory for config, libraries, models and so on. It’s just so much more tidy!

When I began doing this with a simple “news” module, I reached a point where I thought I might have to re-create the simple module admin CRUD and I despaired a bit. I’d written a dashboard for an advanced module before (the configuration form for an import of the Sphider index engine) but that really required a custom input. Would the simple module admin (handled by FUEL’s module controller) really need some ugly, complicated retrofitting?

Fortunately no!! Here’s what I found, and again, FUEL allows an elegant stress free solution. If you follow the tutorials on www.getfuelcms.com, you’ll know that simple modules are recognised by the FUEL admin system when the appropriate array is added to MY_fuel_modules.php, eg:

   1:  $config['modules']['news'] = array(
   2:          'display_field' => 'title',
   3:          'instructions' => '',
   4:          'archivable' => TRUE,
   5:          'preview_path' => 'news/item/{id}'
   6:          ); 

By default, the model for this module will be found in /application/models. By specifying a “model_location” key, the model can instead be found in its advanced module location in /fuel/modules/news/models (in this example) eg:

   1:  $config['modules']['news'] = array(
   2:          'model_location' => 'news', // Looks for model in /modules/
   3:          ...
   4:          ); 

So now, the admin navigation link for Modules/News points to the ordinary CRUD pages, just as if the module were just a “simple” one.

You may already have an array in MY_fuel.php for the same advanced module to appear as a navigable module in its own right too eg:

   1:  $config['modules_allowed'] = array(
   2:      'user_guide',
   3:      'news'
   4:  );

Well, simply remove that module name. Be aware that doing so will remove advanced module functionality (eg prevent config & constants being loaded) from the admin, but if you have no use for these, it's no loss. Then you will have a simple module admin CRUD for an advanced module. The navigation should look something like:

module_nav_01




Note that you can reverse this navigation arrangement if you want. That is, you can retain the advanced module entry in the admin, and not have the simple module navigation, but still make use of the simple modules controller CRUD.

To do this, hide the simple module by adding this key to the module array in MY_fuel_modules.php:

   1:  $config['modules']['news'] = array(
   2:          'hidden' => TRUE,
   3:          ...
   4:          ); 

and add the module name back to the “modules_allowed” array in MY_fuel.php. This will automatically create an admin link as per the {module}.php file array in the advanced modules /config folder eg:

   1:  $config['nav']['news'] = array(
   2:          'news' => 'news'
   3:  );

which will point to url fuel/news, thus being an identical route to the default CRUD pages. The navigation will look like:

module_nav_02

However, since that link is pretty much all that’s needed, a navigation entry of News/news seems redundant. But if you do need the advanced module for custom dashboards as well as a link to the default CRUD system, this is the way to go.

I used v1.0 beta of FUEL CMS for this investigation, but I think the same methods hold true for v0.93.

I've written a more in-depth guide to FUEL advanced modules here

Saturday, 4 August 2012

Caching assets in FUEL CMS

FUEL CMS has several enhancements in terms of classes over plain vanilla Codeigniter. One which I have recently been making more use of is the Asset class.

I’ve been using Andy Clarke’s 320 & Up and in the early version of this, there were a number of CSS and JS files, some conditional for IE.

The Asset class in FUEL CMS allows some neat optimisations regarding CSS & JS that are worth stressing. Typically you can use the css() method to do something simple like:

<?php echo css('base'); ?>

and this will create a <link> tag with an href to the (now cached) base.css file. However, if you have a conditional file for IE you can set the method like this:

<?php echo css('legacy-ie', NULL, 
  array('output' => TRUE, 'attrs' => 'media="screen"', 'ie_conditional' => 'lte IE 6')); ?>

and this will surround the tag with IE conditional comments, and add attributes as specified in the 'attrs' array key.

But there’s more! By combining several css file names as arguments to the css() method, the files can be combined by the Asset class, and with the ‘output’ key set to ‘gzip’, the resulting cache file will be gzipped too. Eg:

<?php echo css('base, home', NULL, array('output' => 'gzip')); ?>   

your server environment permitting of course!

Most of the functionality for the css() method is also available to the js() method too. Eg to combine Imgsizer & Selectivizr scripts and gzip them with IE conditional tags around them:

<?php 
echo js('imgsizer, selectivizr', NULL,
  array('output' => 'gzip', 'ie_conditional' => '(lt IE 9) & (!IEMobile) '));
 ?>

results in the following being rendered in a cached file:

<!--[if (lt IE 9) & (!IEMobile) ]>
<script src="/assets/cache/d370bce01d8e837e3253b2d90ac8c4fb_1325372400.php"
 type="text/javascript" charset="utf-8"></script>
<![endif]—>

If you want to, the ‘output’ array key value can simply be set to TRUE and this will not only gzip but will also clear out whitespace in the source files too. Consult the Asset class guide for more information.

Monday, 25 June 2012

Add a JQuery plugin to FUEL CMS module admin page

When creating a new FUEL CMS module, you get a fully fledged administration CRUD when the module is added to MY_fuel_modules.php. As good as that is, there’s often a need to extend its javascript capabilities in certain situations.

FUEL CMS makes use of a javascript framework named JQX. Its employment in the FUEL admin allows additional code and plugins to be added.

Firstly, let’s demonstrate how JQuery can be hooked into the existing HTML & PHP of the admin. We would want to assign a CSS id or classname to a given field or fields as a selector for JQuery. If the application of a plugin is to a single field, then FUEL CMS assigns an HTML id attribute to the fields within the create / edit page of the module anyway, so that’s catered for. If you wish to assign a custom class name then this can be done within the model of the module, using FUEL’s form_fields() method:

$fields['yourfield']['class'] = 'your-class-name';

So, class or id, we are ready to add functionality via JQX.

First off, we need to create a javascript controller file, using the same name of the module. For example, if the module in hand were named “news” we would create a file called ‘NewsController.js’ and add it to the /fuel/modules/fuel/assets/js/fuel/controller folder. This naming convention allows FUEL to use the script without any further intervention! So when you browse to (for example) /your-site/fuel/news/edit/1 any code within the NewsController.js will be executed. However, the code in that file should be an extension of the existing JQX controller class! So the javascript within should look something like:

   1:  fuel.controller.NewsController = jqx.createController(fuel.controller.BaseFuelController, {
   2:      
   3:      init: function(initObj){
   4:          this._super(initObj);
   5:      },
   6:      
   7:      add_edit: function(){
   8:          this._super();
   9:      }    
  10:  });

This example does nothing but create a new class. To make use of it at all though, we need to add the following to MY_fuel_modules in /config:
$config['modules']['news'] = array(
'js_controller' => 'fuel.controller.NewsController'
);

You may have many other module configurations in this array, but 'js_controller' is required to load the js file in the module. With that done, how do we apply a plugin to a field in the create / edit form?

Again, by convention, the JQX framework looks for plugins on a specific path, in v0.93 of FUEL CMS it is in /fuel/modules/fuel/assets/js/fuel/jquery/plugins. Add the plugin to that folder, and then add the following to the beginning of the js controller script, before the class initialisation (NB the .js file extension is not required):

jqx.load('plugin', 'charCount');

This plugin (charCount.js) happens to be a character countdown script which I want to apply to a textarea field called “summary” within the news module. To instance it we need to add a line to the add_edit function, and create a function that will call the plugin and apply it to the field in question. So our controller code becomes:

   1:  jqx.load('plugin', 'charCount');
   2:             
   3:  fuel.controller.NewsController = jqx.createController(fuel.controller.BaseFuelController, {
   4:      
   5:      init: function(initObj){
   6:          this._super(initObj);
   7:      },
   8:      
   9:      add_edit: function(){
  10:          this._super();
  11:          this.charCounter();
  12:      },
  13:      charCounter: function() {
  14:          // applies char countdown to summary field
  15:          $('#summary').charCount({
  16:              allowed: 120,        
  17:              warning: 20,
  18:              counterText: 'Chars left: '    
  19:          });
  20:      }    
  21:  });

The add_edit() now invokes the charCounter() function on line 11. In turn, this then applies (via JQuery) the character counting plugin code to an element with id “summary”, although as noted above, we could have used a class name instead of an id as a selector. If you are adding more plugins to the module, just use jqx.load() and do something similar with the add_edit function to invoke the plugin.

Powerful stuff, JQX!

I've added a similar walkthrough of adding JQuery functionality to admin modules here.

Friday, 22 June 2012

Tweeting from a FUEL CMS module

Recently a client asked if it were possible to tweet automatically from a news module, such that in publishing a news item, a tweet could optionally be sent too. This article will deal with the basics of creating a tweet relationship within a FUEL CMS news module.

What I envisaged was a checkbox in the module’s create/edit page that indicated the tweet option, and then some post processing to send it. OAUTH would be catered for preferably, and would be invisible to the administrator (eg permission to use the Twitter account would be a condition of being able to use the module in the first place). The link to the tweeted article could be auto generated and shortened using the an API, so again, no user intervention would be required.

The first task was to find a Twitter library, and after prodding several that either didn’t work as expected, or I didn’t understand in time, I used the one supplied by Simon Emms. This offered exactly what I wanted for the module, and was already developed for Codeigniter! Follow Simon’s instructions on how to make use of the library, and you will also need (obviously) a Twitter account to use, and the keys required to use the application including those to auto authenticate the account (ie the consumer key, consumer secret, access key and access secret).

Next,I needed a library to auto shorten the links to the news article. I considered two – one for Google and one for Bitly. Since the Bitly one was also from Simon Emms, that seemed appropriate, but either would have done.

To work

In addition to the checkbox option I had imagined, it seemed a good idea to store whether a tweet had occurred, so my news module MySQL table looked something like

   1:  CREATE TABLE `news` (
   2:    `id` int(11) NOT NULL auto_increment,
   3:    `date_added` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
   4:    `keywords` varchar(255) default NULL,
   5:    `description` varchar(320) default NULL,
   6:    `title` varchar(255) NOT NULL,
   7:    `publish_date` date NOT NULL,
   8:    `summary` varchar(2048) default NULL,
   9:    `content` text,
  10:    `url` varchar(255) default NULL,
  11:    `tweet` enum('yes','no') NOT NULL default 'no',
  12:    `tweeted` int(11) NOT NULL default 0,
  13:    `active` enum('yes','no') default 'no',
  14:    `last_updated` timestamp NULL default NULL,
  15:    PRIMARY KEY  (`id`),
  16:    UNIQUE KEY `id_UNIQUE` (`id`)
  17:  )

The column “tweeted” would store the number of times the article had been posted to twitter (probably only ever once, but you never know), and the “tweet” column would act as a switch to trigger a tweet.


I also made the “tweeted” field readonly, as there is no point rendering it as an editable field, so the news model’s form_fields() method was


   1:  function form_fields($values = array())
   2:  {
   3:    $fields = parent::form_fields($values);
   4:    $fields['tweeted'] = array('readonly' => TRUE, 'comment' => 'Times tweeted (read only)', 
   5:      'order' => 8, 'default' => 0);
   6:    return $fields;
   10:   }



To process the tweet I chose the on_after_save() hook that derives from the  MY_Model class of FUEL CMS. It was as simple as:


   1:  function on_after_save($values)
   2:  {
   3:    if($values['tweet'] == 'yes' && $values['active'] == 'yes')
   4:    {
   5:      $this->load->library('cache'); // required by Twitter lib below
   6:      $this->load->library('twitter');
   7:      if($this->twitter->is_logged_in()) {
   8:          $this->load->library('bitly');
   9:          $tweet = $values['summary'];
  10:          $shortUrl = '';
  11:          $shortUrl = $this->bitly->shorten(site_url('news/item/'. $values['id']));
  12:          $this->twitter->post_tweet($tweet. ' ' . $shortUrl);
  13:          $this->session->set_flashdata('success_other', 'This item has been tweeted successfully too!');
  14:          $this->_updateTweeted($values['id']);
  15:      }    
  16:    else
  17:          $this->session->set_flashdata('success_other', 'Not logged in to Twitter account!');        
  18:    }
  19:    // reset tweet status
  20:    $this->db->set('tweet', 'no');
  21:    $this->db->where('id', $values['id']);
  22:    $this->db->update('news');
  23:  }



The data posted by the module’s form is sent in the $values array. I test for the “tweet” field being positive, and also that the posted item is “active” (eg in published status). The magic with twitter authentication then happens, and if all is well, the Bitly url shortening proceeds, and then the post to Twitter. The _updateTweeted() method is not shown, but this just increments the tweeted field.


I’m using the news module’s “summary” field as the source for the tweet, (and in fact I added a character count to that textarea to warn the user when their limit was up, but I’m not detailing that here).


The success or otherwise of this process is represented in the flashdata messages. I had to edit a core FUEL CMS file (fuel/modules/fuel/views/_blocks/notifications.php) to represent these messages in the admin views, as setting flashdata messages in the on_after_save() method will otherwise see them overwritten by the standard system messaging (hence I use ‘success_other’ key to put them out of harm’s way!). Since tweeting is really only secondary in importance to the form as a whole being saved correctly, the “fail” message will appear after the “Data has been saved” message, rather than in an alert of it’s own.

Wednesday, 30 May 2012

Authenticating pages in FUEL CMS

FUEL CMS uses an ingenious table model to store page variables for its CMS (fuel_page_variables). Such is its design that it is possible to create new variables, or fields, for the Pages module just by adding keys to the array in application/config/MY_fuel_layouts.php. The values stored in the database are under “name” and “value” columns.

It occurred to me that it would be possible to add a boolean field to the array that indicated whether the page required authentication to be viewed. So an admin could check any page in the Pages section as “private” – ie requiring a login.

So adding the key ‘is_private’ (line 8) to MY_fuel_layout.php:

   1:  $config['layout_fields']['main'] =  array(
   2:  'copy' => array('copy' => lang('layout_field_main_copy')),
   3:  'page_title' => array('label' => lang('layout_field_page_title')),
   4:  'meta_description' => array('label' => lang('layout_field_meta_description')),
   5:  'meta_keywords' => array('label' => lang('layout_field_meta_keywords')),
   6:  'body' => array('label' => lang('layout_field_body'), 'type' => 'textarea', 
       'description' => lang('layout_field_body_description')),
   7:  'body_class' => array('label' => lang('layout_field_body_class')),
   8:  'is_private' => array('type' => 'enum', 'options' => array('yes' => 'yes', 'no' => 'no'), 
       'default' => 'no', 'description' => 'Page requires authentication')
   9:  );




creates radio buttons in the “layout variables” section of the Pages edit/create form labelled yes, no. There could be a group requirement and all sorts of sophistication here, but ‘yes’ and ‘no’ will do for now.


How to intercept this variable, and where?

As per Codeigniter, we can use hooks.  In application/config/hooks.php we can add an array to the ‘post_controller’ hook.

   1:  $hook['post_controller'][] = array(
   2:   'class'    => 'MY_auth',
   3:   'function' => 'page_auth',
   4:   'filename' => 'MY_auth.php',
   5:   'filepath' => 'libraries',
   6:   'params'   => array()
   7:   );



Here we identify a class (in application/libraries it so happens) called MY_auth, and a method in it called page_auth(). This will be called after every controller. Note that the array is multi dimensional – the class here can be tacked on to existing hooks by declaring the arrays for a given hook in this manner, see the CI user guide.

In MY_auth we put:

   1:  <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
   2:  class MY_auth {
   3:    var $CI;
   4:    function __construct()
   5:    {
   6:      $this->CI = & get_instance();
   7:      $this->CI->load->library('ion_auth');
   8:    }
   9:      
  10:    function page_auth()
  11:    {
  12:      $this->CI->load->module_library(FUEL_FOLDER, 'fuel_pagevars');
  13:      $vars = $this->CI->fuel_pagevars->retrieve(uri_path(), 'db');
  14:      if(isset($vars['is_private']))
  15:        if($vars['is_private'] == 'yes')
  16:          if(!$this->CI->ion_auth->logged_in())
  17:             redirect('auth/login', 'refresh');
  18:    }
  19:  }



Page_auth() grabs the page variables associated with the current url (specified by uri_path()) from the Fuel_pagevars library in the Fuel modules folder. If one of these is “is_private” and it’s set to ‘yes’, then we whammy the visitor to the auth controller (in this case, courtesy of ion_auth).

Friday, 4 May 2012

Add site-wide authentication to FUEL CMS

FUEL CMS has a simple method of forcing a site-wide password within fuel.php, where you are able to set a "dev_password". However, if you want to add a 3rd party site wide authentication system, you can do so much like you can with a regular Codeigniter install, by editing MY_Controller.

For this example, I'll use Ben Edmunds' ion_auth. It’s very easy to add – unzip the files into the application folder, and setup the SQL in your database.

Open up application/core/MY_Controller.php. In FUEL v0.93, this has no class definition yet, so add the basic class and ion auth requirements:
 
   1:  class MY_Controller extends CI_Controller 
   2:  {
   3:      function __construct()
   4:      {
   5:          parent::__construct();
   6:          $this->load->library('ion_auth');
   7:          $this->load->helper('url');
   8:          if(!$this->ion_auth->logged_in())
   9:          {
  10:                  //redirect them to the login page
  11:                  redirect('auth/login', 'refresh');
  12:          }
  13:      }
  14:  }



Once saved, that should trigger a redirect to ion auth’s login page with any controller inheriting from MY_Controller. If you need to remove that functionality, return MY_Controller.php back to its original state!

Now you need to edit every controller that extended CI_Controller, and change that class name to “MY_Controller” (which itself extends CI_Controller).

That accounts for custom controllers, but not for some core FUEL CMS controllers. The class name swap will also need to occur in page_router.php, Fuel_base_controller.php and Blog_base_controller.php to if you are using that module. I’m prepared to be wrong, but I think that covers all the important controllers, at least for triggering ion auth login.

Thursday, 3 May 2012

Attaching documents to pages in FUEL CMS

The FUEL CMS user guide has a good example tutorial of creating a one to many relationship between simple modules. Recently I tried to do something similar, but using the FUEL admin model for pages, such that you could attach multiple objects (documents in this example) to a page in the admin, using a combo select widget, and display them on the site.

Since this wasn’t as straightforward as I’d hoped, I thought I’d jot down the procedure. I’ve tried to avoid adding all the features you’d need to do this as a real-world project, and have instead concentrated on the essentials. This tutorial relates to v0.93 of FUEL CMS.

Step one

The obvious starting place is to create a couple of database tables: “documents” and “documents_to_pages”.

CREATE TABLE `documents` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `summary` varchar(255) DEFAULT '',
  `file` varchar(255) NOT NULL DEFAULT '',
  `publish_date` datetime,
  `author` varchar(255) NULL default '',
  `tags` varchar(1024) NULL default '',
  `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `active` enum('yes','no') DEFAULT 'no',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `documents_to_pages` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `page_id` int(11) NOT NULL,
  `document_id` int(11) NOT NULL, 
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

These are just examples, you may want more or less fields, or a different charset. The "documents" table will hold the file details, including a publishing date and file name, and the “documents_to_pages” is a plain vanilla look-up table to relate the key (id) of the document against the key (also named id) of the fuel_pages table (this is FUEL’s core page table - many of the layout fields are stored in “fuel_page_variables”).

Once these are added to your FUEL database schema, we can go on with the models for the 2 tables, and set about the model for pages.

Step two

Here’s the document model in full:

   1:  <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
   2:   
   3:  require_once(FUEL_PATH.'models/base_module_model.php');
   4:   
   5:  class Documents_model extends Base_module_model {
   6:       
   7:      public $record_class = 'Document';
   8:       
   9:      function __construct()
  10:      {
  11:          parent::__construct('documents');
  12:      }
  13:    
  14:      function form_fields($values = array())
  15:      {
  16:          $fields = parent::form_fields($values);
  17:          $upload_path = assets_server_path('_uploads/documents/');   
  18:          $fields['file_upload'] = array('type' => 'file',
  19:                          'upload_path' => $upload_path, 'overwrite' => FALSE);
  20:          return $fields;
  21:      }
  22:       
  23:      function on_after_delete($where)
  24:      {
  25:          $CI =& get_instance();
  26:          $CI->load->model('documents_to_pages_model');
  27:          if (is_array($where) && isset($where['id']))
  28:          {
  29:              $where = array('document_id' => $where['id']);
  30:              $CI->documents_to_pages_model->delete($where);
  31:          }
  32:       }
  33:  }
  34:   
  35:  class Document_model extends Base_module_record {
  36:   
  37:  }

Mostly this is standard FUEL CMS fare. In the form_fields() method we set an upload path where the file will be stored – you may want this to be different. We also configure the “dummy”upload field (dummy in the sense it doesn’t exist in the database, but by convention, it will store the file name in the field "file").

Using the on_after_delete() hook, we can erase any look-up records related to the deleted document. Not necessary but tidy!

Step three

The "documents_to_pages_model" can look like this:

   1:  <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
   2:   
   3:  class Documents_to_pages_model extends MY_Model {
   4:   
   5:      public $record_class = 'Document_to_page';
   6:   
   7:      function __construct()
   8:      {
   9:          parent::__construct('documents_to_pages');
  10:      }
  11:   
  12:      function _common_query()
  13:      {
  14:          $this->db->select('documents_to_pages.*, documents.title');
  15:          $this->db->join('documents', 'documents_to_pages.document_id = documents.id', 'left');
  16:          $this->db->join('fuel_pages', 'documents_to_pages.page_id = fuel_pages.id', 'left');        
  17:      }
  18:   
  19:   function getItemsByPage($page_id) 
  20:  {
  21:        $this->db->select("documents.id, documents.title, documents.file, documents.summary, 
             DATE_FORMAT(documents.publish_date,'%Y-%m-%d'), 
             UPPER(REVERSE(SUBSTRING_INDEX(REVERSE(documents.file),'.',1))) AS file_type", FALSE);
  22:        $this->db->join("documents", "documents_to_pages.document_id = documents.id", "left");
  23:        $this->db->join("fuel_pages", "documents_to_pages.page_id =  fuel_pages.id", "left");
  24:        $this->db->where("documents.active", "yes");
  25:        $this->db->where("documents.publish_date <=", "CURRENT_TIMESTAMP", FALSE);
  26:        $this->db->where("documents_to_pages.page_id", $page_id);
  27:        $result = $this->db->get("documents_to_pages");
  28:        return $result;
  29:        }
  30:  }
  31:   
  32:  class Document_to_page_model extends Data_record {
  33:  }

Nothing much unusual here. The getItemsByPage() method will be used to display a list of records on a given page. The active record methods (select, join, where) ensure the records are active and published.

Step four

Next we need to modify the pages_model.php file found in the Fuel directory (/fuel/modules/fuel/models/). We have to add the combo select field which will allow files to be selected and “attached” to the page. To do this, we edit the form_fields() method:

   1:  function form_fields($values = array())
   2:  {
   3:      $related = array('documents' => 'documents_to_pages_model');
   4:      $fields = parent::form_fields();
   5:      $fields['date_added']['type'] = 'hidden';
   6:          
   7:  // ******************* NEW RELATED DOCUMENT FIELD BEGIN 
   8:  // NB pages controller needs updating as of v0.93 to ensure $values is passed to form fields
   9:  // eg $fields = $this->model->form_fields($saved);
  10:      $CI =& get_instance();
  11:      $CI->load->model('documents_model');
  12:      $CI->load->model('documents_to_pages_model');
  13:      $document_options = $CI->documents_model->options_list('id', 
           'title', array('active' => 'yes'), 'title');
  14:      $document_values = (!empty($values['id'])) ? 
           array_keys($CI->documents_to_pages_model->find_all_array_assoc('document_id', 
           array('page_id' => $values['id']))) : array();
  15:      $fields['documents'] = array('label' => 'Documents', 'type' => 'array',  
           'class' => 'add_edit documents', 'options' => $document_options,  
           'value' => $document_values, 'mode' => 'multi');
  16:  // ******************* NEW RELATED DOCUMENT FIELD END
  17:      
  18:      $yes = lang('form_enum_option_yes');
  19:      $no = lang('form_enum_option_no');
  20:      $fields['cache']['options'] = array('yes' => $yes, 'no' => $no);
  21:      return $fields;
  22:  }

The comments indicate the new field "documents" we are inserting into this method, but line 3 also indicates the relationship with the documents_to_pages_model. The values of this new field will be whatever is retrieved with the find_all_array_assoc() method of the MY_Model class we extended with the Documents_to_pages_model defined earlier. Note that there is a comment about the pages controller on line 8. It's commonly the case that the form_fields() argument $values contains the saved form data, but as of v0.93 of FUEL, this isn’t so of the pages model. So we must add the argument $values = array() as per line 1, and then the pages_controller also needs to be edited to send that argument in the first place, and that’s simple enough to do. Open up /fuel/modules/fuel/controllers/pages.php and find this line (line 117 of the current code):

$fields = $this->model->form_fields();

and change it to:

$fields = $this->model->form_fields($saved);

Easy!

We have not finished with the pages_model however. We add this hook:

   1:  function on_after_save($values)
   2:  {
   3:      $data = (!empty($this->normalized_save_data['documents'])) ? 
           $this->normalized_save_data['documents'] : array();
   4:      $this->save_related('documents_to_pages_model', 
           array('page_id' => $values['id']), array('document_id' => $data));        
   5:  }

This inserts the document id's and page id into the look-up table. And then we should delete related look-up records when a page is deleted, so we add a line to the on_after_delete() hook:

   1:  function on_after_delete($where)
   2:  {
   3:      $this->delete_related(array(FUEL_FOLDER => 'pagevariables_model'), 'page_id', $where);
   4:      $this->delete_related(documents_to_pages_model, 'page_id', $where);
   5:  }

Line 4 is the addition.

Step five


The admin will not display the new document model yet, not until this line is added to MY_fuel_modules.php (located in application/config):

$config['modules']['documents'] = array(); 

It should now be possible to add some test documents to the documents module in FUEL's admin. Once you have done that, take a look at the pages module too, and create or edit a page - you should see the combo select widget with the files you added to the documents module on the left. Use the combo and add one or more documents to the right hand side, and hit save. You should now see the saved files remain on the right hand selection area.

That’s about all on this topic! Bear in mind that the lookup table could be made more generic, such that documents could be associated with any module (not just pages), or even to be a store for the relationship of any module to any other module. I’ll also leave aside how to display the related documents, but that’s relatively straightforward.

Thanks to David McReynolds, lead developer of the FUEL CMS project, for helping me out with some of the issues I encountered. The forums for FUEL are massively helpful, and I recommend visiting there for help and advice.
My top artists