In this tenth episode of the CodeIgniter From Scratch screencast series, we will be exploring the Calendar library. We are also going to utilize the database class and jQuery AJAX. I will show you how to build a simple and CSS-styled calendar page, which will have the ability to store and display content for each day.
Catch Up
- Day 1: Getting Started With the Framework
- Day 2: Database Selecting Methods
- Day 3: Sending Emails
- Day 4: Newsletter Signup
- Day 5: CRUD
- Day 6: Login
- Day 7: Pagination
- Day 8: AJAX
- Day 9: File Uploading and Image Manipulation
- Day 10: The Calendar Library
Day 10: The Calendar Library
Other Viewing Options
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for more daily web development tuts and articles.


teşekkürler Burak…
nice one again ;) awesome…
Yh nice tut. ;)
Yeah! Awesome tutorials! I like them! :)
keep going! ++
Nice tut, thank u very much.
Thanks Burak. You’re fast :)
This is a great series. I’ll have to watch this soon…
Hello,
Is there any way to make a part 2 of this tutorial that can show us how to use the Calendar library to show events across multiple days? And what I mean by that, is, showing an event by giving it a unique color and having that color span the same number of days that the event goes on for.
All of the tutorials I come across for calendars that talk about multi-day events don’t explain how to show the event spanning multiple days in the calendar itself.
Thank you so much! This tutorial was helpful.
Just add the event to as many days as the event spans. do your magic in this loop:
function get_calendar_data($year, $month) {
$query = $this->db->select(‘date, data’)->from(‘calendar’)
->like(‘date’, “$year-$month”, ‘after’)->get();
$cal_data = array();
foreach ($query->result() as $row) {
$cal_data[substr($row->date,8,2)] = $row->data;
}
return $cal_data;
}
Remove the date as the primary key and setup sequential keys (auto-increment.) Have a starting date and an ending date (or have a record for each day of the event if information could vary each day.)
As for the color and spanning, you could come up with an easy algorithm for margin-top based on the time of day (do not allow overlap times.) You could co0me up with a color scheme based on time slot too I suppose.
You know, I never really thought of this – I’m working with a system that is actually quite broken, but it does show multi-day events. The problem with what I have is that for events that start or end on the 1st or last day of the month, they don’t show up in the calendar – my guess is because of something to do with DST.
But thank you for the insight! Sometimes you just need a different brain. :)
pretty cool :P
Great Tutorial.
Great Tut!
Would it be possible to extend this tut to show how you could create a calendar date picker, like airline websites use?
I’m working on a calendar for a restaurant, and they sell some items online. In their online order form, currently I have a pickup date that has to check extensively to make sure the restaurant is open on the date specified for pickup.
It’s very odd rules I had to program, such as—Closed on Sundays & Monday, unless it’s Mother’s day, Father’s Day, Memorial Day, or Labor Day.
While I’ve managed to compile all the blackout dates I need, I’m looking for a way to create a calendar from which the pickup date could be selected, and blackout dates can’t be selected.
Is this possible w/ what you’ve shown already?
Thanks again for your great Tuts!
I found an excellent JavaScript solution to that problem at http://www.frequency-decoder.com/2009/09/09/unobtrusive-date-picker-widget-v5/ .
Awesome,definitely going to watch this tomorrow.Thanks!!
Great tutorial, only one question
Why didn’t you use if-then? (I don’t know exactly how it’s called, sorry)
So something like this:
$year = ($year)?$year:date(‘Y’);
$month = ($month)?$month:date(‘M’);
I think that it’s easier in this way, however it depends on the person, so just take this as a note : D.
Tom, they’re called “ternary operators”.
You bring up a great point.
They’re great as I use them all the time, but for someone who is just learning PHP and CodeIgniter I think it would cause some confusion compared to a regular if-elseif-else statement.
And I believe the video is trying to make sure people clearly understand the code from more of a beginner level.
Couldn’t have said it better myself.
Merhaba,Burak biliyormusun bilmiyorum ama Aptana Studio’da PDT leri indiremiyorum hata veriyor ve ileri geri tuşları falan çalışmıyor 2.0da ya da manuel olarak PDT leri nasıl kurabılırım . Bunun hakkında bilgiğin bi çözüm var mı yardımcı olabılırmısın.Teşekkürler…
Who knows about the solution of Aptana Studio’s PDT plug-in problem or how can i install manually those…
I use Eclipse… And Zend plugins…
eclipse php ide:
http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/galileo/SR2/eclipse-php-galileo-SR2-win32.zip
and the zend plugin:
http://downloads.zend.com/pdt/debugger/org.zend.php.debug_feature-I20081217.zip
Cem i tried to install the plugin by using Aptana, but i failed too..
O yüzden de eclipse’e döndüm…
Pek bir fark da göremedim, hatta yok sanırım?
Good tutorial.
codeigniter is awesome, I hope nettuts keeps delivering these tutorials! Can we see some xml parsing with codeigniter next?
second this, almost creating a kind of API style thing that let’s you pass parameters to your application and codeigniter spits out an xml response…
id be interested in that as well
Kohana dude…. only kohana
Very cool! Again another good tutorial.
This is the first of these lessons that I have not been able to run on my server. I can connect to the data base. I get a 404 error. I have set the routes.php file to call mycal.php but still no luck. Any suggestions?
404 doesn’t mean that its a database error. It could be that you are using the incorrect url because your host environment doesn’t support the rewrite instructions in the .htaccess. Try using index.php in the url as if the .htaccess file didn’t exist. Sorry if this is wrong, just the first thing that came to mind. Try to debug and give us more details and we can help you out more.
Hello Burak,
Thank you for the great tutorials!
I have a question about Aptana. In the video I see that your IDE is autocompleting your code. For example when you want to create an array, you see a list where you can choose array. How did you do this, I can’t get that to work. Sorry for the bad english.
I am using an older version, not the new PDT versions (which sucks to be honest).
Thanks Burak. Glad that you covered some Ajax.
Codeigniter calendar class does not have a preference for next/last year. Some of you may be interested in this article about Codeigniter event calendar. This does not use CI’s calendar class, however it uses jquery to display events with tooltips and for date input. It has also links to next/last year and can be used javascript disabled.
Can not watch full movie :( it stops after 10 or less minutes!
But this ten minutes were great to watch….this series of CodeIgniter motivated me to use CodeIgniter as my framework for my new project….
thanks Net tuts…but please let me know how I can watch full movie.
Dont ever stop! :)
I’m aware that a 404 error is a file not found. I pointed out the database connection to show how far along the progress was. The behavior to me seems that the controller cannot be found. How can I test to see if I get to the controller? I put this echo statement in the first line of the display function of the controller class:
function display($year = null, $month = null) {
echo (‘I am in the controllers ‘);
But I never see it:
No one else having a problem?
Brilliant, thanks!
Thanks Burak! Is there a demo of this anywhere?
No, sorry. But it should be easy to install from the source code.
- change the base url in config.php
- create the database and table from the video
- change the database.php settings
great !
@rouse I cant get it to work either. I can connect to the database, but the whole scripting ignores my model except for the part that says i have data in the database.
All I can see is a small calendar with no previous/next indicators or any formatting of the template Burak made. In fact it follows the template I have in the Calendar library.
The only thing I have different here is I do not pull my applications folder out, I leave it where it is.
I also work live on the server, no WAMP
Just for kicks I tried to change the other small calenders on the site, took the calendar library out of autoload and tried to add next/previous on using the user guide, and absolutely nothing changes. I don’t think there is anything wrong with Burak’s script, obviously I have something else going on.
I would love to find out what it is. All of my other ci_series worked and are still working so there is something subtle going on. Later today I will try to load a fresh version 1.72 and patch in the changes from this tutorial.
WBR
Do you have mod_rewrite enabled?
Convention over Configuration. That’s the big buzz phrase for MVC (and what makes it so damned cool really.) That means if you supply the right URL, you will hit the right controller. Otherwise, you get a 404. I’d follow the advice that Taylor gave you earlier in the comments (hint: Like Burak intimated you probably do not have mod_rewrite enabled to either enable it or put the index.php back into your config.php file. I don’t think Jeffrey ever used mod_rewrite in the past episodes but don’t quote me on that.)
Great work Thankyou
waiting for AJAX Pagination with Codeigniter
waiting for Ajax pagination with selected rows..!
Good job Burak! Thanks a lot.
Give us more AJAX – pagination would be great to see next. BUT in the same time please show how to deal with it if the JS is disabled in users browser.
@rouse I went into the calender library and set the show next previous to TRUE and all of a sudden everything worked.
Brad:
Did not help here. What I am clear about, is that it is a routing problem within this CI project on my machine.
I am seeing the CI error page and all the other tutorials still work.
I have not found the difference yet.
Burak,
Thanks for a great screencast! I’m learning so much through watching this series!
One thing I noticed after completing the project is that it won’t save data to any of the days that are single digits (1-9). It saves the data to any of the two digit dates though. I’d imagine it has something to do with the date format in the database requiring dates in two digit format, like 01 instead of just 1.
How would I fix this?
The easiest way is to change the type of the date field from date to varchar in phpmyadmin.
Depends on how your data is coming out of the database and the following line:
$cal_data[substr($row->date,8,2)] = $row->data;
if your date string is 2010-1-1 than substr(8,2) will be off (it’ll get nada in this example) You’d probably do better to use split or use a database function to return the day only.
$query = $this->db->select(‘DAY(date)’, FALSE)->select(‘data’)->from(‘calendar’)
->like(‘date’, “$year-$month”, ‘after’)->get();
The problem here is the generate() function; generate() parses data used to place information in the calendar cells. This is in the calendar library of CodeIgnite. I would say this is a problem that CodeIgnite should fix. It would only take a couple of lines. Any volunteers? :)
Try this:
In the library file Calendar.php at around line 195 there is a while loop:
// Build the main body of the calendar
while ($day <= $total_days) {
$out .= "\n";
Then look for the for loop that follows and add the code that starts “if ($day < 10) {
So the new block of code should look like this:
while ($day temp['cal_row_start'];
$out .= “\n”;
for ($i = 0; $i temp['cal_cell_start_today'] : $this->temp['cal_cell_start'];
if($day 0 AND $day <= $total_days) {
So you want to add the str_pad method
Pretty nice tutorial, again.
Awesome tutorial Burak,
This could be useful for a Task Management application which I was going to create, didn’t realise jQuery / Ajax was actually that easy. haha. Pretty awesome stuff.
Can someone do some kohana tuts….. Serriously man….. Kohana pwns…
kOHANA > CODEIGNITER
Hey that’s really ace, thanks!
exellent once again!
Please keep on teaching us!
Can you give more info on working with sessions, cookies, zip and xml?
and how to use a Zend-framework-file in CodeIgniter, e.g. Zend_Acl
Dude… your seriously awesome!
I really appreciate people like yourself who really do so much for the community like this.. haven’t gone through all of yours tutorials yet but I will at some point when I get a free hour or two.
Thanks again!
I have 2 questions though…
- what about unobtrusive javascript? If JS is disabled, you won’t be abled to add/edit the data.
- what happens if you click in an empty cell? e.g. March has some empty cells.
To make the empty cells unclickable, you could add a quick check in your jQuery:
$(‘.calendar .day’).click(function() {
if ($(this).html() != ‘ ’) {
// code to run for the clickable cells
}
});
A more elegant solution would be to modify the calendar template, but this works for a quick fix.
Ok, that code displayed wrong. It’s meant to be checking for an nbsp entity in the 2nd line. If you view your page source, you will see that all the blank cells have a non-breaking space as their html content.
how can i install manually PDT on aptana studio 1.5 ?
Burak Guzel:
Would you resolve the issue on the calendar with storage and retrieval of single day data. The tool is pretty useless without being able to save and retrieve data between day 1 and day 9.
Thank you!
Great, I was looking forward to a calendar use for codeigniter! Going to check it asap
It looks like my earlier reply was truncated. To fix the single digit issue try this: Search for the Build string in library file Calendar.php and add the str_pad code. Hope this helps some of you.
// Build the main body of the calendar
while ($day temp['cal_row_start'];
$out .= “\n”;
for ($i = 0; $i temp['cal_cell_start_today'] : $this->temp['cal_cell_start'];
if($day < 10) {
$day = str_pad($day, 2, '0', STR_PAD_LEFT);
}
Ok, I came up with a simpler solution. Just add this:
if($day 0 AND $day 0 AND $day <= $total_days)
{
if($day<10)
$day = str_pad($day, 2, '0', STR_PAD_LEFT);
…
It works!
Victor:
What file and where do you place this code?
Thanks!
WBR
Sorry, my comment was truncated. Ok, here is the problem. In the Calendar library go to the generate function. There you will find a section of the code that builds the main body of the calendar (it is documented likewise).
// Build the main body of the calendar
The problem statement is found here…
if (isset($data[$tempday]))
I will explain why and what to do later.
Upps, it was supposed to read
if (isset($data[$day]))
Anyway, that statement is not detecting the data in an array when the days are less than 10 (Why?? No clue, before this tutorial, I hadn’t really played with PHP!) So when the calendar information is written here…
$out .= str_replace(‘{day}’, $day, str_replace(‘{content}’, $data[$day], $temp));
It’s not placing the info from the first digit days. My solution is…. (I hate this limit on my comments!)
Test for days that are single digit before the “if (isset($data[$day])).”
To fix this just copy this code and paste it right before the “if(isset…” statement
if($day<10)
$day = str_pad($day, 2, '0', STR_PAD_LEFT);
This will fix the issue, but now you will have your days appearing as.. "01, 02, etc" I fixed that creating a temporal variable for "$day"
if($day<10)
$tempday = str_pad($day, 2, '0', STR_PAD_LEFT);
and then just replacing the $day variable here (NOTICE the only change needed was REPLACING $day WITH $tempday).
$out .= str_replace('{day}', $day, str_replace('{content}', $data[$tempday], $temp));
Again, I am by no means a PHP programmer, but this works. If someone can explain this, I will be very happy to learn why "if isset" is not working with single digit days.
I´m having the same issue… but still can’t fix it with your explanation
If you cast the day as an int, ever thing works fine. CI is interpreting it as a string.. Example
foreach($Q->result() as $row) {
$cal_data[(int)substr($row->date, 8, 2)] = $row->data;
}
+1 for Zack Kitzmiller’s solution. Much easier than tinkering with Calendar.php and risking a breakage!
Zack Kitzmiller’s code is much better solution to this problem compared to the above solutions:
foreach ($query->result() as $row) {
$cal_data[(int)substr($row->taskDateStart,8,2)] = $row->taskName;
}
Zack Kitzmiller’s code is much better solution to this problem compared to the above solutions.
I looove CodeIgniter!
Please continue to publish CI tutorials :)
Can’t wait to get home this evening and watch it.
Great screencast.
Cheers from germany
Burak, thanks for the tutorial, really useful.
One thing – is that appropriate to use AJAX to reload a page?
wouldn’t it be better to change the value of the row dynamically by jQuery instead of reloading the page? I guess the beauty of ajax is the reload – free experience..
anyway, it is really great that you keep the good level up!
Yeah that would be a good option. As soon as confirmation comes from the ajax call, you can update the cell without reloading the page.
I have a problem with the .htaccess archive. If I put something like this (acording with my folder structure “http://localhost/Code_Igniter/calendar/…”) I can´t see anything on my browser :
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /Code_Igniter/calendar/index.php/$1 [L]
Thanks for this Great TUTS!
You should put the /calendar AFTER /index.php, so it last line looks like
RewriteRule ^(.*)$ /Code_Igniter/index.php/calendar/$1 [L]
Hope it helps!
Really Great!
How can I get multiple events for each day to appear when fetched from a database?
Hi all!
I´m right now writing my first project with CodeIgniter but I have run in to a problem concerning the encoding.
Outputting a string width php echo like so: echo ‘åäöÅÄÖ’; works fine and is displayed as åäöÅÄÖ,
but trying to output the same string just using åäöÅÄÖ returns a bunch of squares…
so, anything outputted by php (strings or values from a DB) works great, but trying through html doesn’t .
please help me out!
Hi all!
I recently started my first CodeIgniter project, I really like it but i have run into a problem.
when i try to output special characters (åäö) i get squares instead, however this is only when outputting using html. echo ‘åäö’; displays correctly but not åäö.
can someone help me?
I had the same problem. I just added this line at the top of the calendar_view file.
hm.. cant place php text.. try to complete this..
header( ‘Content-type: text/html; charset=utf-8′ );
Burak,
Thanks for this wonderful tutorial man. I really appreciate you doing these for us. They are very good. I was wanting to know if you could do one with CodeIgniter and php generated XML files.
Im having a weird problem here, if i call the parent constructor ( parent::Model(); ) in my model constructor, i get an error that says: “Fatal error: Call to a member function item() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/CodeIgniter_Calendar/system/libraries/Language.php on line 64″ but if i dont call the parent (model) constructor everything works fine. Does anybody know why this happens??
Thanks a lot for this CodeIgniter series, they have been a real boost in my deeloping skills.
Cheers from Cancun!
That is because you tried to name your $conf variable $config, which is a reserved CodeIgniter Variable.
Use $conf or $cal_config to resolve.
I think that is a version mismatching situation. Have you touched that? have you updated? in case of not, download latest CI version, if still getting error, ask Godgle :p
Hey Burak! Congrats, really nice tutorial and useful continuation of jeff’s work.
In the previous case, it was better example of working with usability concepts, I mean the submit button and functions were well called so if user has JS deactivated, site works well. Just as recommendation, it would be great not to do both way, but at least to mention “make your website thinking about users”.
Same recommendation than above (Klon comment), greater to have success function like: element.html(day_data); instead of window.reload, where element is the $(this) outside the $.ajax (meaning the selected day TD in this case).
And also you could use $(function(){ /* blahblah */ }); instead of doc.ready
NETTUTS ROCKZ.
Your tutorials are really great. Keep up the good work. I am relatively new to codeigniter. I was wondering if you could do a tutorial on complex search forms that include text fields, select boxes, checkboxes and radio buttons. I am having trouble finding a great solution to pass that form data to a page that paginates the results. This is an issue I am finding many people are having.
The content in the “today” day in the calendar is not showing, just copied the contents from my installation of CI.
I’m still looking for it.
Someone has the same issue?
Nice article, it’s a great start point to my to-do list app.
Thank you
Where can i get database for this project.