Easier Search||Filtering With Controller::postConditions()

In the old days, I remember being extra lazy when it comes to requests for filter/search functions. I would be lazier if the conditions includes lots of fields.

Stumbling upon postConditions, this flipped what I felt about creating a filter function.

So here’s what we are going to try, we’ll create a filter function for messages as example. Let’s assume you have the table, model, controller and some CRUD done and working for messages.

Let us begin by creating the view first since we’re getting the filter conditions from the form. It’s this file: ‘app/views/messages/filter_messages.ctp’.

 
<h2>Filter Messages</h2>
<?php
echo $form->create('Message', array('action' => 'filter_messages'));
echo $form->input('message');
echo $form->input('from');
echo $form->end('Submit Filter');
?>
<hr />
<h2>Filter Results: </h2>
<?php
//display apa kita jumpa kat sini
foreach($messages as $message):
    echo $message['Message']['message'] ;
    echo "<hr />";
endforeach;
?>

Then add the filter function to the app/controllers/messages_controller.php.

 
function filter_messages() {
        //simple initialization for the variable that'll carry the result
        $messages = array();
        //checks if we sent something to filter via the form (remember sent items go to $this->data)
        if($this->data) {
 
            /*
             * here comes postConditions
             * first parameter is the posted value,
             * 
             * the second parameter (array('message' => 'LIKE'))
             * tells postCondition for the fields we're looking at and what type of
             * condition we want to use for that field item. So in this case, we want to use 'LIKE' for field 'message'
             * therefore the sql generated will look similar to "SELECT * FROM messages as Message WHERE Message.message LIKE '%whatever%' "
             * 
             * the third parameter, will tell what is the boolean condition among each
             * condition we set for the find (you know like if we want 'message' is like 'b' AND the message came from 'dude')
             * 
             * last and quite least (heh), if we set true, only the fields we set in the second parameter will be considered. 
             * if false, any field in $this->data will be used. nifty huh.
             */
            $conditions = $this->postConditions( $this->data,
                                                 array('message' => 'LIKE'),
                                                 'OR',
                                                 false
                                               );
 
            //the usual find() function.
            $messages = $this->Message->find('all', array('conditions'=> $conditions));
        }
 
        //sends result to the view.
        $this->set('messages', $messages);
 
    }
?>

That’s it!

An additional note: Controller::postConditions() doesn’t mean you have to use the data posted but you can also ready your own array in the usual $myarray['Model']['field1'] format and use that as parameter.

<?php
 $tobefiltered = array('Message' => (
                        array(
                               'message'=>'this is my message',
                               'created' => '2009-09-09 21:09:09',
                               'from' => '013xxxxxxxxxx'
                              )
                       );
 $condition_generated = $this->postConditions($tobefiltered);
 
?>

Second Day On Building Drupal Module

I’m learning how to build a Drupal CMS module for a website I’m partially supporting.

The module is simply to allow a student to send in queries to a panel of teachers. A registered student submits a question, the panel gets a notification via email that a question was submitted and then the panel would answer if they want to. Quite a simple module but since I’m just starting to do it the Drupal way, it would take more time than the usuals.

Maybe.

After a day of going through the tutorials, API and whatnot, I think I’ve got enough to get the module up and running. But patience is a virtue and over-confidence is the fall of many many men. So let’s just study more of this so that we can do this properly and avoid problems later on.

note: Considering to just mutilate Drupal’s comment module to add in what I need.

Re-doing Python.Org.My

The macho way of doing stuffs is by doing it all yourself.

The smarter way is using what people already done and make it run with your needs. So we’re trying out Pinax for python.org.my. I got it running fine on my machine but for some reason it just wouldn’t start on the server.

Currently python.org.my is on diamanda, a django forum (we decided to stick to django apps since it’s something we want to learn and work on) and since Pinax is also running on django, I figured it would work out of the box. Of course it would, just make sure to get the requirements right.

I spent half a day on the console trying to figure out why pinax was giving me the ‘OperationalError: unable to open database file’. I googled and there was someone there who had the same problem but the solution they gave him doesn’t seem to work on my case.

Then it hit me… the server was running on python2.4. I guess pinax wants version 2.5. That’s the only thing I can think of that is causing the problem. Lets see if I can get the server owner or Misbah to upgrade….

Post-Lamp2Win

Okay I lost!

But it was worth losing. There were really good people there.

I was assigned to TextPattern cms and the code structure was pretty easy to understand. They didn’t have (yet) any db abstraction and looking at the code didn’t feel like doing any until later. The unstable code in subversion seems to point out that they want to provide this. Or… it could be just to support some mysql forks.

So I started with putting in the DB layer from their newer version into the stable one. Then after several mishaps later, I had a broken MSSQL support and basically gave up after, in my opinion, lobotomising good code. So in the end I lost.

It was good fun. Quite a while since I had to juggle stuffs in my life and this is good practice.

Lamp2Win

lamp2win.com

Sometimes I’m not sure what I’m doing and I have to tell you that this is one of them. I registered for the Lamp2Win contest to extend a selected application into a php/IIS/MSSQL environment. I’ve never done IIS. I don’t know anything about MSSQL. Luckily I have some experience in php.

I’m counting on that to help me get through.

Gee… the acronym is WIMP (Windows IIS MSSQL PHP).

After registration I noticed that people will vote for their favourite and this will be 40% mark. Darn. I’m not exactly Mr Popular material.

Oh well, maybe I’ll get new friends around the community of whatever application they’ll assign me to.

Back To Ubuntu

A month ago I had a laptop failure that, cool enough, resulted in me having a better laptop. I love my company and my company loves the programmer. hehe.

So from a Toshiba Tecra S2 (that occasionally wouldn’t even start sometimes. Possible fix below) to a Compaq nw9440. Sweet.

Since I have to setup a new OS anyway, I decided to give Fedora 10 a try since my first Linux experience back in 2001 was on a Red Hat. At first Fedora 10 was cool. It starts up nicely, didn’t like how they did the gdm login though. There was a minor update manager upgrade hiccup at first but I got that fixed by changing the repositories (I think).

After a month of use, Ubuntu 9.04 was released and I guess I’m just a Ubuntu fan. So I downloaded Ubuntu, installed it last night and left the laptop on for the updates, extra application installation and copying my old home directory to this new one.

In the morning, I have a fresh Ubuntu 9.04 ready for playfulity productivity.

And then for some reason I couldn’t update/install because the repository http://my.archive.ubuntu.com keeps on timing out. So I edited the source.list file to get the files from archive.ubuntu.com, reload the package manager and that managed to get it working.

Anyway, I guess I’m close to getting development environment up and running again. Just needs to load up xampp (love you guys because all I need to do is copy over the lampp folder to my new /opt/ ).

//Toshiba Tecra s2 possible no-start fix. Possibly could ruin your life forever too so beware!
1. Try taking out the battery and just use the power supply.
2. Syukri of QIPMC mentioned that he opened up his machine and found that the screw near the keyboard or heatsink was loose. Tightening that up seems to make the problem go away.
3. Go change the motherboard. This was what I did twice.
//endOfToshiba Tecra s2 possible no-start fix.

So let see what happens after a month of using Ubuntu. :)

Invitation for Maulidur Rasul 2009 at Masjid Negara, Kuala Lumpur

Sorry if I posted this a bit late…

All Muslims are invited!

Update: The chairman of Al-Wariseen, Sy Afeef Uddin Al-Gailani will be on TV3’s Malaysia Hari Ini to talk about this at 7am on 10th April

Date : 11th April 2009 (Saturday)
Time : 5.00 – 10.00 pm
Venue : Masjid Negara Kuala Lumpur

Itenary:

4.45 pm Arrival of guests
5.15 pm Introduction by the MC
5.20 pm Welcoming speech by the Deputy Chairman of Al Wariseen Trust
5.30 pm Speaker 1 – Prof. Dr. Rafi’ Al-Ani (Mufti of Iraq)
6.00 pm Speaker 2 – Habib Umar HAmid Al-Gailani (Makkah)
6.30 pm Qasidah Burdah by Syed Abbas Alawi Al Maliki Al Hasani (Makkah)
6.50 pm Dr. Ahmed Omar Hashem (former Rector of Al Azhar University, Egypt)
7.00 pm Arrival of VIP guest
7.05 pm Speaker 3 – Dr. Muhammad Uthman El-Muhammady (Lecturer ISTAC)
7.25 pm Adzan & Solat Maghrib
7.45 pm Speaker 4 – Prof. Dr. Ali Gomaa Mohamed Abdelwahab (Mufti of Egypt)
8.31 pm Adzan & Solat Isyak
8.40 pm Speaker 5 – Ustaz Fuad Al Maliki
8.50 pm Introduction and recital of Maulud Ad-Daiba’ie by Habib Hassan Bin Mohammed Salim Al Attas (Singapore) and Syed Abbas Alawi Al Maliki Al Hasani (Makkah)
9.20 pm Doa’ by the Chairman of the Al Wariseen Trust, Sheikh Maulana Afeef Uddin Al Gailani
9.30 pm Dinner

Launching the Prayers For Forgiveness Blogger Widget!

You can get it here.

Blessed with this idea after Ramadhan but hope everybody, and myself, find it especially useful for the next Ramadhan.

This blogger widget randomly displays one prayer (english translation) from the seventy prayers written down by Hasan Al-Basri, a respected scholar born in 21 AH and brought up in the house of Umm Salama (ra).

You can order the book at amazon. It’s right over here. Highly recommended!

As of writting, there’s about 5 prayers in the database. I’ll fill it up soonest. :) . (Update: All done.)

regards.

/** Update **/
I guess this stuff is done! Works fine so far.

jquery sebagai framework terbaik

Membina satu aplikasi web kini hampir mewajibkan penggunaan javascript. Ini disebabkan penggunaan konsep AJAX secara meluas. Rasanya selepas AJAX diperkenalkan, pelbagai framework javascript mula mendapat perhatian kerana AJAX itu pada dasarnya sedikit rumit terutama apabila mengambil kira bagaimana setiap browser meng-implementasi AJAX itu sendiri. Tambahan pula, framework-framework itu keluar dengan special effect untuk mencanggihkan(merumitkan?) lagi interface aplikasi kita.

Jquery adalah satu framework yang begitu popular kerana ia direka untuk memudahkan kita memasukkan AJAX, special effects serta pelbagai funtion-function lain melalui penggunaan plugin. Ianya mudah untuk mereka yang tidak biasa dengan javascript dan juga cukup solid untuk mereka yang sudah master.

Baru-baru ini jquery dipilih oleh Nokia dan Microsoft untuk disertakan dalam produk-produk mereka. Ini boleh dibaca pada blog jquery. Aplikasi mobile disertakan dengan javascript? :)

Dengan dua nama besar ini menggunakan jquery, rasanya sesiapa yang ingin mencari framework javascript yang mantap bolehlah memilih jquery dengan hati yang senang.

menggunakan cakephp’s beforeFind

I found out that on cakephp 1.2 RC3 you must use the new $Model->find() style or the query will break.

1
2
3
4
5
6
7
8
9
10
11
//in the controller use this...
$this->Post->find('first', $params);
 
//instead of the 'old' style...
$this->Post->find($conditions);
 
//so that in the model, you can do something like this...
function beforeFind($queryData) {
          $queryData['conditions']["`Post`.`post_type`"] = "personal";
          return($queryData);
}

Ada masanya kita perlu mengubah condition carian-carian kita pada satu-satu model. Selain meletakkan condition query itu setiap kali kita melakukan find, kita boleh menggunakan function callback pada model iaitu function beforeFind(). Ia menerima satu parameter iaitu $queryData, variable array yang menyimpan maklumat untuk find seperti ‘conditions’, ‘limit’, ‘joins’ dan sebagainya.

Tidak seperti tertera pada dokumentasi cakePHP, sebenarnya untuk beforeFind kita dapat memulangkan samada boolean (true/false) ataupun satu array . Jika kita memulangkan boolean, ia samada menjalankan query tersebut atau tidak: true untuk teruskan query, false untuk tidak membuat query.

Apa yang tidak disebut ialah jika kita mahu menukarkan apa2 pada syarat query itu, kita perlu buat perubahan pada $queryData dan pulangkan $queryData itu (return ($queryData)). Contoh…

1
2
3
4
5
6
7
/**
* ini contoh untuk menambahkan syarat pada find kita. Ini pada model AccomodationTravelBooking
**/
function beforeFind($queryData) {
     $queryData['conditions'][] = "`AccomodationTravelBooking.booking_type` = 'accomodation'";
     return($queryData);
}

Contoh diberi pada dokumentasi cakephp ialah jika kita tidak membenarkan query dilakukan mengikut syarat2 tertentu:

1
2
3
4
5
6
7
8
9
10
11
/**
* ini contoh untuk menambahkan syarat pada find kita. Ini pada model AccomodationTravelBooking
**/
function beforeFind($queryData) {
    //kononnya id 44 tu satu ID yang kita tak benarkan untuk diquery
    if($queryData['conditions']['AccomodationTravelBooking.id'] == 44) {
       return(false);
    }
 
    return(true);
 }

nota update: tak baca betul2, camtu la resultnya.

RSS for Posts RSS for Comments