Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 2

Exclusive offer: get 50% off this eBook here
jQuery 1.3 with PHP

jQuery 1.3 with PHP — Save 50%

Enhance your PHP applications by increasing their responsiveness through jQuery and its plugins.

$23.99    $12.00
by Kae Verens | October 2009 | MySQL Content Management Open Source PHP Web Development

Read Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 1 here.

Deleting events

After creating, moving, and editing events, we might come across a case where the edit form is different from the create form. There is no reason why you would want to delete an event that has not yet been created, so there is no reason to add a delete button to the "Create Event" form.

We have a choice—add the delete button to the section at the bottom of the modal dialog, next to Save and Cancel, or add it to the body of the form itself.

I always try to add delete buttons and links where I think they cannot be hit by accident. Therefore in this case, I chose not to add it to the row of buttons at the bottom. Instead, I placed it in the form itself where there's little chance it will be clicked by accident while saving or closing the form.

Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 2

And even then, if the link is clicked, there is always a secondary "Are you sure?" confirmation box.

Client-side code

In the calendar_edit_entry function in calender.js, change the beginning of the $.getJSON call to this:

$.getJSON('./calendar.php?action=get_event&id='+calEvent.id,
function(eventdata){
var controls='<a href="javascript:calendar_delete_entry'
+'('+eventdata.id+');">[delete]</a>';
$('<div id="calendar_edit_entry_form"
title="Edit Calendar Entry">'
+'<div style="float:right;text-align:right">'+controls+'</div>'
+'event name<br />'
+'<input id="calendar_edit_entry_form_title"
value="'+eventdata.title+'" /><br />'
+'body text<br />'
+'<textarea style="width:400px;height:200px"
id="calendar_edit_entry_form_body">'
'+eventdata.body+'</textarea></div>'
).appendTo($('body'));
$("#calendar_edit_entry_form").dialog({

The only real change is to add the controls variable, which lets us create more buttons if necessary, and add that variable's contained HTML to the form.

The only control there at the moment is a delete link, which calls the calendar_delete_entry function when clicked.

Add this function now:

function calendar_delete_entry(id){ 
if(confirm('are you sure you want to delete this entry?')){
$('#calendar_edit_entry_form').remove();
$.getJSON('./calendar.php?action=delete_event&id='+id,
function(ret){
$('#calendar_wrapper').weekCalendar('refresh');
}
);
}
}

Server-side code

On the server side, we add a case to handle deletes:

 case 'delete_event': // {
$id=(int)$_REQUEST['id'];
unset($_SESSION['calendar'][$id]);
echo 1;
exit;
// }

All it needs to do is to unset the session variable.

With that completed, you now have the finished basics of a calendar, where you can create events, move them around, edit them, and delete them.

Walk-through of the calendar so far

We've built the basics of a weekly calendar, and before we go on to discuss recurring events, let's take the time to walk through the calendar so far with a simple example.

Let's say you have an appointment on Tuesday at 2 pm with a business partner. You add that by clicking on that time, as follows:

Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 2

You think that the meeting will go on for about two hours, so you resize it:

Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 2

Now Bob calls up early on Tuesday to say that he's not going to be able to make it, and suggests moving it to Wednesday at 1 pm. You drag the event over:

Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 2

He also says that he won't be able to make it, but Sally would be there. So, you click on the event and edit the form accordingly:

Wednesday comes, and of course, something has come up on your end. You call Sally and explain that you won't be able to make it, and delete the event by clicking on the event, and then clicking on the delete link.

Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 2

Simple and quick. What more would you want? Let's do some recurring events.

Recurring events

Sometimes you will want to have the same event automatically populated in the calendar on a recurrent basis. For example, you go to lunch every day at 1 pm, or there might be a weekly office meeting every Monday morning.

In this case, we need to come up with a way of having events recur.

This can be simple or very complex. The simplest method is what we'll demonstrate in this article.

The simple method involves entering a frequency (daily, monthly, and so on) and a final date, where the events stop recurring.

On the server side, when it is asked to create that recurring event, the server actually iterates over the entire requested period and adds each individual event.

This is not extremely efficient, but it's simple to write, and it's not likely that anyone would be placing years-long recurrent events on a very regular basis, so it's justifiable.

The more complex method is to only create events that are actually visible in the week you are viewing, and whenever you change the week, you check to see if there are any events that are supposed to recur that week but are not visible.

This is arguably even less efficient than the simple method, but it would allow us to be a little more flexible—for example, to leave out the final date so that the events just keep recurring.

Anyway, given that there are no major drawbacks to either method, we will choose the simpler method.

Client-side code

On the client side, recurrences are created at the same time as the recurrence of the first event. So, we edit the "Create Event" form.

In calendar.js , adapt the calendar_new_entry function by replacing the form-creation line with this:

var recurbox='<select id="calendar_new_entry_form_recurring">'
+'<option value="0">non-recurring</option>'
+'<option value="1">Daily</option>'
+'<option value="7">Weekly</option>'
+'</select>';
$('<div id="calendar_new_entry_form"
title="New Calendar Entry">event name<br />'
+'<input value="new event"
id="calendar_new_entry_form_title" /><br />'
+'body text<br />'
+'<textarea style="width:400px;height:200px"
id="calendar_new_entry_form_body">'
event description</textarea>'
+recurbox+'</div>')
.appendTo($('body'));
$('#calendar_new_entry_form_recurring')
.change(calendar_new_get_recurring_end);

This adds a select box below the body text area, requesting the user to choose a recurring frequency (defaulting to non-recurring).

Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 2

When the select box is changed, the function calendar_new_get_recurring_end is called.

This function is used to request the final recurring date.

We could use a plain old text field, but jQuery UI includes a really cool date widget, which allows us to request the date and have it stored in our own choice of format. I've chosen yyyy-mm-dd format, as it is easy to manipulate.

Add this to calendar.js:

function calendar_new_get_recurring_end(){ 
if(document.getElementById('calendar_new_recurring_end'))
return;
var year = new Date().getFullYear();
var month = new Date().getMonth();
var day = new Date().getDate();
$('<span> until <input id="calendar_new_recurring_end"
value="'+year+'-'+(month+1)+'-'+day+'"
style="font-size:14px"
class="date" />'
+' </span>'
).insertAfter('#calendar_new_entry_form_recurring');
$('.date').datepicker({
'dateFormat':'yy-mm-dd',
'yearRange':'-10:+50',
'changeYear':true
});
}

That creates an input field after the dropdown box, and when it is clicked, a calendar pops up:

Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 2

Whoops! What's happened here is that the date pop up's z-index is lower than the modal dialog. That can be corrected by adding this CSS line to the  < head > section of calendar.html:

<style type="text/css">
#ui-datepicker-div{
z-index: 2000;
}
</style>

When reloaded, the calendar now looks correct:

Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 2

Great! Now, we just need to send the data to the server.

To do that, change the Save button's $.getJSON parameters in the calendar_new_entry function in calendar.js to these (new parameters are highlighted):

'body':$('#calendar_new_entry_form_body').val(), 
'title':$('#calendar_new_entry_form_title').val(),
'recurring':$('#calendar_new_entry_form_recurring').val(),
'recurring_end':$('#calendar_new_recurring_end').val()

And we're done on the client side.

Server-side code

On the server side, the save switch case is going to change considerably, so I'll provide the entire section:

case 'save': // { 
$start_date=(int)$_REQUEST['start'];
$data=array(
'title'=>$_REQUEST['title'],
'body' =>$_REQUEST['body'],
'start'=>date('c',$start_date),
'end' =>date('c',(int)$_REQUEST['end'])
);
$id=(int)$_REQUEST['id'];
if($id && isset($_SESSION['calendar'][$id])){
if(isset($_SESSION['calendar'][$id]['recurring']))
$data['recurring']=$_SESSION['calendar'][$id]['recurring'];
$_SESSION['calendar'][$id]=$data;
}
else{
$id=++$_SESSION['calendar']['ids'];
$rec=(int)$_REQUEST['recurring'];
if($rec) $data['recurring']=$id;
$_SESSION['calendar'][$id]=$data;
if($rec && $rec==1 || $rec==7){
list($y,$m,$d)=explode('-',$_REQUEST['recurring_end']);
$length=(int)$_REQUEST['end']-$start_date;
$end_date=mktime(23,59,59,$m,$d,$y);
$step=3600*24*$rec;
for($j=1,$i=$start_date+$step;$i<$end_date;$j++,$i+=$step){
$data['start']=date('c',$i);
$data['end']=date('c',$i+$length);
$nextid=++$_SESSION['calendar']['ids'];
$_SESSION['calendar'][$nextid]=$data;
}
}
}
echo 1;
exit;
// }

OK. From the data point of view, we've added a single field, recurring, which records the first event in the series. This is needed when deleting recurring events that are not needed anymore.

When editing an existing event, all that's changed is that the recurring field (if it exists) is copied from the original before the event is overwritten with fresh data (shown highlighted).

The real action happens when creating a new event. If a recurring period is required, then the event is copied and pasted at the requested frequency from the event's first creation until the expiry date. This is figured out by counting the seconds, and incrementing as needed.

We can immediately see that recurring events work. Here's an example of a week's lunch hours created from the new recurring method:

Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 2

You can shift individual events around, and even delete them, without affecting the rest.

jQuery 1.3 with PHP Enhance your PHP applications by increasing their responsiveness through jQuery and its plugins.
Published: October 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Deleting recurring events

Finally, though, we need a way to cancel the events altogether. (Let's say lunch has become too expensive to buy.)

We will do this the same way as we did the original "Delete Event" functionality. The only difference is that this method will delete all events from the selected one onwards that were created from the same original event.

Client-side code

We are going to add a new control to the edit form, below the delete link.

In calendar.js , edit the calendar_new_entry function, and add the highlighted code as shown here:

$.getJSON('./calendar.php?action=get_event&id='+calEvent.id,
function(eventdata){
var controls='<a href="javascript:calendar_delete_entry('
+eventdata.id+');">'
+'[delete]</a>';
if(+eventdata.recurring)controls+='<br />'
+'<a href="javascript:calendar_delete_recurrences('
+eventdata.id+')">'
+' [stop recurring]</a>';
$('<div id="calendar_edit_entry_form"

This code will add a second link, stop recurring, which will appear only on events that are part of a recurring sequence. (Remember that all recurring events have a "recurring" variable set to a non-zero value.)

Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 2

Then we need to add the referenced calendar_delete_recurrences function:

function calendar_delete_recurrences(id){ 
if(confirm('This will delete this entry and all following recurrences
of this entrynAre you sure you want to do this?')){
$('#calendar_edit_entry_form').remove();
$.getJSON('./calendar.php?action=delete_event&id='
+id+'&recurrences=1',
function(ret){
$('#calendar_wrapper').weekCalendar('refresh');
});
}
}

When clicked, a pop up will verify if you are certain that you want to remove the events, then will call the server with the request before refreshing.

Server-side code

On the server side, because this is basically a deletion, we will amend the existing delete_event case, so that it can handle both standalone and recurring events.

This is a significant change, so I'll provide the full rewrite of the case:

case 'delete_event': // { 
$id=(int)$_REQUEST['id'];
if(!isset($_SESSION['calendar'][$id])) exit;
$d=$_SESSION['calendar'][$id];
if((int)$_REQUEST['recurrences']){
$start=$d['start'];
$r=$d['recurring'];
for($i=1;$i<$_SESSION['calendar']['ids']+1;++$i){
if(isset($_SESSION['calendar'][$i])
&& isset($_SESSION['calendar'][$i]['recurring'])
&& $_SESSION['calendar'][$i]['recurring']==$r
&& strcmp($_SESSION['calendar'][$i]['start'],$start)>0
){
unset($_SESSION['calendar'][$i]);
}
}
}
unset($_SESSION['calendar'][$id]);
echo 1;
exit;
// }

What this does is to go through all recorded events, check that the event is equal to, or later than, the date of the clicked event, and ensure that the event has the same original event tagged in its recurring field.

With that done, we now have a pretty good calendar, which can handle one-off events and simple recurrences of events.

For an exercise, you could try adapting the system to use a database instead. Also, try adapting the system so that moving a recurring event will also move all the following events by the same amount.

Summary

In this article, we built a calendar using the jquery-week-calendar plugin, which can handle one-off and recurring events.

Along the way, we also got to use jQuery UI's modal dialogs, and also its datePicker plugin, which allows dates to be picked from a pop up calendar.

[ 1 | 2

jQuery 1.3 with PHP Enhance your PHP applications by increasing their responsiveness through jQuery and its plugins.
Published: October 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Kae Verens

Kae Verens is an owner manager of the web-development company Webworks.ie and is currently secretary of the Irish PHP Users Group. He has been writing in JavaScript since the mid 90s, and in PHP since the late 90s. Kae is the creator of the file management system KFM, the CMS WebME (used by Webworks.ie for over 200 separate clients), and the author of the Packt book jQuery 1.3 with PHP.

 

Books From Packt

Joomla! with Flash
oomla! with Flash

Joomla! 1.5 SEO
Joomla! 1.5 SEO

Symfony 1.3 Web Application Development
Symfony 1.3 Web Application Development

Plone 3 for Education
Plone 3 for Education

JBoss Tools 3 Developers Guide
JBoss Tools 3 Developers Guide

PHP Team Development
PHP Team Development

JBoss RichFaces 3.3
JBoss RichFaces 3.3

jQuery UI 1.6: The User Interface Library for jQuery
jQuery UI 1.6: The User Interface Library for jQuery

 

 

 

Your rating: None Average: 4.2 (5 votes)
Source files by
You can download souce files from here
can you add source files to this ?? by
can you add source files to this ??

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
8
q
r
v
9
H
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software