Over a million developers have joined DZone.

CodeIgniter: Getting Started with the Calendar Class

The CodeIgniter calendar class is available for creating data-driven calendars for your web apps. This article illustrates it with a simple tasks web app.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

The CodeIgniter calendar class is available for creating data-driven calendars for your web apps. What follows is a walk through on how I implemented the calendar class for a simple tasks web app.

So, the app I wanted was a simple list of tasks that could be checked off when completed and a way to keep some notes for the task too.

I’m going to assume you already have some experience with PHP. It would be useful if you know the basics of CodeIgniter too.

Setting Up for the CodeIgniter Calendar

CodeIgniter doesn’t take much setting up. Here are the basic tasks:

  • Create a new local, virtual domain (I called mine http://tasks.dev). I use MAMP Pro, but any local setup that you would normally use will suffice.
  • Create a new MySQL database called tasks
  • Add a table called tasks_list. (Schema below)
  • Configure the database in application/config/database.php
  • Add the database and sessions library to application/config/autoload.php. Also, autoload the URL helper.
  • Add a .htaccess for pretty URLs, and set up the site info in application/config/config.php.

All of the above are standard CodeIgniter set up operations. The user guide will help you out.

The Database Schema

CREATE TABLE `tasks_list` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(200) DEFAULT NULL,
 `body` text,
  `due` date DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
   `completed` tinyint(1) NOT NULL DEFAULT '0',
   PRIMARY KEY (`id`)
) ENGINE=InnoDB

Implementing the CodeIgniter Calendar

The calendar I wanted was a month display, with the ability to click through other months with a simple hyperlink. CodeIgniter’s calendar supports that. I also wanted to attach a link to tasks stored in the database on the individual days of the month.

To get the basic calendar working, we can get some setting up done on the constructor of the welcome controller:

class Welcome extends CI_Controller 
{
    public function __construct()
    {
        parent:: __construct();
        $this->load->model('tasks_model');
        $prefs = array (
            'show_next_prev'  => TRUE,
             'next_prev_url'   => 'http://tasks.dev/welcome/index'
        );

        $this->load->library('calendar', $prefs);
     }

Here, we are setting up some preferences and passing them to the calendar class. We want the next and previous links, and they will need a URL to operate on. That is what is being passed in the prefs array. We then load the calendar class and pass in those preferences.

I opted to do this in the constructor so that I could call the calendar from any method in the controller.

You’ll notice that I have also loaded a model called tasks_model which we’ll be using shortly.

To generate the calendar, we just need this:

 $this->calendar->generate($this->uri->segment(3), $this->uri->segment(4));

The URI segments are values passed in from the next and previous links. What happens if we are on the homepage, though? There will be no URI segments in that case. Well, we can check for them, and then offer an alternative:

 public function index()
 {
     $month = (!$this->uri->segment(4)) ? date('m') : $this->uri->segment(4);
     $tasks = $this->tasks_model->get_tasks($month);
     if($tasks == 0)
     {
         $data['cal'] = $this->calendar->generate($this->uri->segment(3), $this->uri->segment(4));
     }
     else
     {
         $data['cal'] = $this->calendar->generate($this->uri->segment(3), $this->uri->segment(4), $tasks);
     }

     $this->load->view('welcome_message', $data);
 }

The ternary operator checks to see if the 4th URI segment is set. If it’s not, we use the date function to get the current month. Otherwise, we can use the 4th segment. CodeIgniter will load the current month for us.

Notice also, we are retrieving the tasks for the given month via our tasks_model. If we get no tasks, we just load the calendar normally, if there are tasks, then we pass in the array of links to “wire up” the links to the active days.

Getting the Tasks

Here is the model:

class Tasks_Model extends CI_Model
{
    public function __construct()
    {
        parent:: __construct();
    }

    public function get_tasks($month)
    {
        $sql = "SELECT DAY(due) As day, due, title FROM tasks_list WHERE MONTH(due) = " . $month;
        $q = $this->db->query($sql);
        $num = $q->num_rows();

        if($num > 0)
        {
            foreach($q->result() as $row)
            {
                $data[] = $row;
            }

            foreach($data as $d)
            {
                $out[$d->day] = (int)$d->day;
                $out[$d->day] = "http://tasks.dev/welcome/show/" . date('Y/m/d', strtotime($d->due));
             }
             return $out;
            }
            else
            {
                return 0;
            }        
    }

I’ll say straight away that there is probably a better way of doing this. I tried several things, but getting the data first and then creating the array for the calendar seemed to work best. The array of data that gets passed to the calendar has very precise requirements. Notice that I’m ensuring that the day is definitely an integer.

I’m also adding the date from the due field of the database at the end of the URL, so we can properly retrieve the tasks for that given day.

One More Thing…

So, at this stage, we have a calendar and we have days with tasks linked… to nowhere, yet. Well, the hyperlink is fine, but we need a new method in the controller so that we can pass the tasks for that day to a view.

Let’s have a look:

  public function show()
    {
        $year = $this->uri->segment(3);
        $month = $this->uri->segment(4);
        $day = $this->uri->segment(5);
        $date = $year . '-' . $month . '-' . $day;
        $data['day'] = date('d/m/Y', strtotime($date));
        $data['tasks'] = $this->tasks_model->day_tasks($date);
        $this->load->view('show', $data);
    }

All that’s happening here is that we have collected the date components from the URI string, reassembled it as a date, and then sent it as a string to the view. We also sent the $date variable through to a method in our tasks_model:

public function day_tasks($day)
{
    $sql = "SELECT * FROM tasks_list WHERE due = '" . $day . "'";
    $q = $this->db->query($sql);
    if($q->num_rows() > 0)
    {
        foreach($q->result() as $row)
        {
            $data[] = $row;
        }
            return $data;
        }
        else
        {
            return 0;
        }
}

First, I know I could have used Active Record here. I know, right? I didn’t though because I’d had some trouble getting the data out in perfect format to populate the calendar (as I mentioned earlier). So, when things get tough, I go “old skool”.

There is nothing special about this method. What it does demonstrate, is how important that $date variable is.

Finally…

So, there it is, a simple implementation of the CodeIgniter Calendar class. You could continue to build out this app by adding a master task list for checking items off, a form for adding tasks, and so on.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
codeigniter ,php ,mysql

Published at DZone with permission of Andy Hawthorne, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}