monetization

Fullcalendar with PHP and CodeIgniter - Adding Events - Part 3

Now that we have created our database table, it's time to setup our frontend actions that allow us to add events.

This tutorial is a continuation of our FullCalendar with PHP and CodeIgniter series. View previous parts:

For this tutorial, we'll be using Bootstrap's modal display. It's a seamless fade-in area that allows us to keep the user on the same page as the calendar and present them with a form. If you have no idea what I'm talking about, it'll all make sense soon!

In order to use Bootstrap's modal component, we need to include Bootstrap's javascript library:

Modify and add the following code application/views/calendar/index.php:

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Now we just copy and paste the bootstrap modal form into our HTML. You can find the default code on bootstrap.com Modify application/views/calendar/index.php:

<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
             <div class="modal-header">
                 <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                 <h4 class="modal-title" id="myModalLabel">Add Calendar Event</h4>
             </div>
             <div class="modal-body">
                  Form Goes Here
             </div>
             <div class="modal-footer">
                 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                 <button type="button" class="btn btn-primary">Save changes</button>
             </div>
        </div>
    </div>
</div>

This is the default modal form. Before we make any changes to it, we need to modify the code so that when you click on an event in the FullCalendar, the modal will popup.

In order to do this, we need to modify the dayClick event in FullCalendar. This event is what is called whenever you click on one of the squares on FullCalendar.

Modify application/views/calendar/index.php:

var date_last_clicked = null;

$('#calendar').fullCalendar({
    eventSources: [
    {
        events: function(start, end, timezone, callback) {
            $.ajax({
                url: '<?php echo base_url() ?>calendar/get_events',
                dataType: 'json',
                data: {                
                    start: start.unix(),
                    end: end.unix()
                },
                success: function(msg) {
                    var events = msg.events;
                    callback(events);
                }
            });
       }
    },
    ],
    dayClick: function(date, jsEvent, view) {
        date_last_clicked = $(this);
        $(this).css('background-color', '#bed7f3');
        $('#addModal').modal();
    },
});

The first thing you should notice is the new variable we made: date_last_clicked. This is so we can keep track of the day we clicked on last because inside the dayClick function we change the background of the tile we have just clicked on (to show the user what date they are adding an event to).

The last line in the dayClick function is calling the modal() method on our #addModal modal. This will force the modal to popup for us.

So now that we have implemented our day clicking functionality, have our modal sorted out, it's time to setup the form that is going to be used to create the events. We need to go back to our modal code and modify it:

Modify application/views/calendar/index.php:

<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Add Calendar Event</h4>
      </div>
      <div class="modal-body">
      <?php echo form_open(site_url("calendar/add_event"), array("class" => "form-horizontal")) ?>
      <div class="form-group">
                <label for="p-in" class="col-md-4 label-heading">Event Name</label>
                <div class="col-md-8 ui-front">
                    <input type="text" class="form-control" name="name" value="">
                </div>
        </div>
        <div class="form-group">
                <label for="p-in" class="col-md-4 label-heading">Description</label>
                <div class="col-md-8 ui-front">
                    <input type="text" class="form-control" name="description">
                </div>
        </div>
        <div class="form-group">
                <label for="p-in" class="col-md-4 label-heading">Start Date</label>
                <div class="col-md-8">
                    <input type="text" class="form-control" name="start_date">
                </div>
        </div>
        <div class="form-group">
                <label for="p-in" class="col-md-4 label-heading">End Date</label>
                <div class="col-md-8">
                    <input type="text" class="form-control" name="end_date">
                </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <input type="submit" class="btn btn-primary" value="Add Event">
        <?php echo form_close() ?>
      </div>
    </div>
  </div>
</div>

We've modified the modal to now include a form that will be processed to the function calendar/add_event. We use CodeIgniter's form_open() function we just sets up the basic form details for us.

We have added four input boxes: Event Title, Event Description, Event Start Date and Event End Date. The Event Title is the label used on the event when it's displayed on the FullCalendar.

The Start and End Dates use a particular date-format for storing in our Calendar. You can use a plugin like DateTimePicker which allows you to select the date and time but for this tutorial, we'll just rely on you typing in the correct format:

Y/m/d H:i

Which is basically Year/Month/Day Hour:minute i.e. 2017/03/18 14:30

So now we have setup our form, we can now go onto creating the controller function add_event() which will process the data submitted.

Modify application/controllers/Calendar.php:

public function add_event() 
{
    /* Our calendar data */
    $name = $this->input->post("name", TRUE);
    $desc = $this->input->post("description", TRUE);
    $start_date = $this->input->post("start_date", TRUE);
    $end_date = $this->input->post("end_date", TRUE);

    if(!empty($start_date)) {
       $sd = DateTime::createFromFormat("Y/m/d H:i", $start_date);
       $start_date = $sd->format('Y-m-d H:i:s');
       $start_date_timestamp = $sd->getTimestamp();
    } else {
       $start_date = date("Y-m-d H:i:s", time());
       $start_date_timestamp = time();
    }

    if(!empty($end_date)) {
       $ed = DateTime::createFromFormat("Y/m/d H:i", $end_date);
       $end_date = $ed->format('Y-m-d H:i:s');
       $end_date_timestamp = $ed->getTimestamp();
    } else {
       $end_date = date("Y-m-d H:i:s", time());
       $end_date_timestamp = time();
    }

    $this->calendar_model->add_event(array(
       "title" => $name,
       "description" => $desc,
       "start" => $start_date,
       "end" => $end_date
       )
    );

    redirect(site_url("calendar"));
}

This function takes our form data and processes it, then sends it to our model for storing in the database. Our variables $name, $desc, $start_date and $end_date all come from our form fields we just created in index.php.

We need to format our dates correctly using the FullCalendar format that it expects. For this example, we format the dates to: Y-m-d H:i:s using PHP's DateTime function. We then get the timestamp of this date to store in the database.

We made our add_event() model function back in FullCalendar PHP part 2, so all we need to do is popular the model with data.

Finally, we redirect back to the calendar after adding the event. Now you should have a working Calendar that allows you to add events! 

In the final part, we'll do modifying/editing events :)

Resources




Enjoyed that? Check These Posts Out

Setup Amazon Affiliate API with PHP - Product Advertising API 5.0 (2020)

Fullcalendar with PHP and CodeIgniter - Database Events - Part 2

Sager NP8377 Gaming Laptop Review

Using Datatables with CodeIgniter Tutorial

...
monetization

Article Comments

Let us know your thoughts below by adding a quick comment!

14/06/2017

zordein

I've been following along with this guide and was going smooth up til the end here; the modal window pops up, seems to work fine, however when I click Add Event I get: Fatal error: Uncaught Error: Call to a member function nohtml() on null in the controller on the "$name = $this-&gt;common-&gt;nohtml($this-&gt;input-&gt;post("name"));" line

Reply

14/06/2017

patchesoft

Oops! Thanks for that. I've updated the blog post to remove that bit of code (it's a function I created in my own system to clean out any HTML content). Try with the new code now and let me know if that helps :)

Reply

14/06/2017

Alyssa

Hi, this is very guide to my project. Is it possible to fetch date that selected and automatically will show that date in modal as a $start_date? :))))

Reply

14/06/2017

patchesoft

Yep! You'll need to take a look at the dayClick: function in the JavaScript code. It has a date variable passed to it; you just need to extract it and then attach it to the input.

Reply

30/08/2017

Monika

Since PHP 5.3 it's necessary to set the timezone. for ex. date_default_timezone_set('Europe/Paris'); in function __construct()

Reply

30/08/2017

Monika

Nowadays appear a problem with submit button - doesn't work. The have to be moved line up (up to line: ) and form_close offcourse have to be moved too - line down :)

Reply

12/09/2017

Najihah

I've follow the coding but why the popup for add event didn't show up?

Reply

12/09/2017

Patchesoft

@Najihah Do you have a link to your example?

Reply

13/09/2017

Najihah

@Patchesoft

No, I don't have any link.

Reply

27/09/2017

Marvin Gifford

Hi!

It's working now! Thank you very much for the help! :)

Reply

09/05/2018

Cigale

@Patchesoft
I followed your page but I could not see the popup.

Reply

06/10/2018

JA

@Patchesoft
Is it possible to make just one modal to add and edit, i mean i will just use a one modal instead of creating a new one for edit.

Reply

05/12/2018

nawaz

TypeError: $(...).modal is not a function


$('#addModal').modal();

Reply

28/04/2020

yufei Cao

Type: Error

Message: Call to a member function format() on bool

I can't solve this error

Reply

Leave A Comment