All posts tagged CakePHP

Zend Framework 2 : The proper way to set application path in Javascript Object

Storing application path inside Javascript object is a way to avoid “hard coded” URL inside your Javascript file.  It is pretty common to have like this in your Javascript file :

$.ajax({
    type: POST,
    url: 'http://localhost/my-website/register',
    data: dataJSON
})

That approach is completely fine. However, when you need to deploy your application, you need to manually change all the URL to match with your server. The solution that I have been using for quite a long time is setting up Javascript object that contains path to my application.

In CakePHP, this can be easily done by using URL method inside Router Class. Here is the sample :

$cbunny = array(
    'APP_PATH' => Router::url('/',true)
);
echo $this->Html->scriptBlock('var CbunnyObj = ' . $this->Javascript->object($cbunny) . ';');

In Zend Framework 2, you have to rely on serverUrl and basePath to achieve the same thing. Here is the proper way to do it in Zend Framework 2 :

        <script type="text/javascript">
            //<![CDATA[
                var CMSObj = {
                    "APP_PATH":"<?php echo $this->serverUrl() . $this->basePath() ?>/"
                };
            //]]>
        </script>

 

Rails set up namespace and redirect from namespace

In order to differentiate between admin actions and users actions, you can set up what called “namespace” in your rails apps. The basic idea of this feature is you will have different controller and view files for each role in your application.

This concept is similar with prefixes in CakePHP. However,  CakePHP allows you to put different action in one controller file, while in rails you have to create different controller and view file for the new namespace. Here is the sample namespace code that I put in my routes.rb file :

  namespace :admin do
    resources :users
    resources :products
    resources :categories
  end

The code means that users, products and categories will have admin namespace. The next step is to create new folder in your controller and view folder called “admin”. Here is the screenshot ( see the directory browser on the left hand side ) :

Put the template and controller files inside these folders. You have to add Admin:: in front of the class definition of your controller file. So it’s gonna be like this :

class Admin::UsersController < ApplicationController

After you set up everything done, you can try to access your apps through http://your-url/admin/controller-path ( ex: http://localhost:3000/admin/users ). It should automatically pick the controller and view files from admin folder. And if you want to redirect to the original route, you have to add '/' in front of the controller name. Here is the code :

redirect_to :controller => "/sessions",:action => "new"

It means you will redirect the user to session controller outside of the namespace and load "new" action. That's all.

Auto redirect in CakePHP jQuery AutoComplete

Demo : http://cbunny.rudylee.com/autocomplete_redirect

Demo source code : https://github.com/rudylee/cbunny

In my previous post ( http://blog.rudylee.com/2011/07/25/jquery-ui-autocomplete-in-cakephp/ ) we have successfully integrated the jQuery AutoComplete with CakePHP with a little bit hacky way. Now we gonna add another feature that can redirect user to our desired place when they click the result value in the AutoComplete ( try the demo for more details ).

So let’s start the coding ( I assume you have integrated the jQuery UI AutoComplete in your apps, if you haven’t, just read my previous post ), so basically what we need to do are divided into 4 steps:

  • Wrap the jQuery UI AutoComplete search field in a form tag.
  • Add a hidden field which will hold the ID of the result.
  • Add ‘select’ option into the helper.
  • Set up the action that will handle the form submit

Here is the sample of the action code:

[php] function admin_autoComplete() {
if (!empty($this->data)) {
$this->redirect(array(
‘controller’ => ‘users’,
‘action’ => ‘view’, $this->data['Guest']['id']
));
}
$this->autoRender = false;
$guests = $this->User->getGuests(array(
‘conditions’ => array(
‘OR’ => array(
‘User.name LIKE’ => ‘%’ . $_GET['term'] . ‘%’,
‘User.surname LIKE’ => ‘%’ . $_GET['term'] . ‘%’
)
)
));
echo json_encode($this->User->autoComplete_encode($guests));
}[/php]


Just ignore line 8 and so, we gonna focus on line 2 to 7. In that line, I redirect the user to the view action which based on the Guest ID which I got from the form. You can change the controller/action in this section. I hope everything are clear. Cheers.

jQuery UI AutoComplete in CakePHP

Demo : http://cbunny.rudylee.com/autocomplete

Demo source code : https://github.com/rudylee/cbunny
The post to add auto redirect feature into the AutoComplete : http://blog.rudylee.com/2011/12/12/auto-redirect-in-cakephp-jquery-autocomplete/
You can copy the modified Ajax and Javascript helpers from here https://github.com/rudylee/topping

Last week I was trying to use jQuery UI Autocomplete in my CakePHP apps. However, CakePHP Ajax and Javascript helpers don’t support jQuery by default. After googling a little bit, I found that this guy ( http://www.cakephp.bee.pl/ ) already made Ajax and Javascript helpers for jQuery.

So I just copied these helpers from his site and put it into my apps. It’s done ? obviously not. It turned out that the autocomplete script that he using in his helper is the old one ( http://docs.jquery.com/Plugins/autocomplete ).

Thus, I had to add a method inside that helper to use jQuery UI autocomplete. Here are the sample codes ( you can copy from my github for the complete file, this one is just snippet ) :

 /**
     * Options for auto-complete editor.
     *
     * @var array
     */
    var $autoCompleteOptions = array(
	'select', 'source'
    );

    /**
     * Create a text field with Jquery UI Autocomplete.
     *
     * Creates an autocomplete field with the given ID and options.
     * needs include jQuery UI Autocomplete file
     *
     * @param string $field DOM ID of field to observe
     * @param array $options Ajax options
     * @return string Ajax script
     * check out http://jqueryui.com/demos/autocomplete/
     */
    function autoComplete($field, $options = array()) {
	$var = '';
	if (isset($options['var'])) {
	    $var = 'var ' . $options['var'] . ' = ';
	    unset($options['var']);
	}

	if(isset($options['source'])) {
	    $options['source'] = "'".Router::url($options['source'])."'";
	}

	if (!isset($options['id'])) {
	    $options['id'] = Inflector::camelize(str_replace(".", "_", $field));
	}

	$htmlOptions = $this->__getHtmlOptions($options);
	$htmlOptions['autocomplete'] = "off";

	foreach ($this->autoCompleteOptions as $opt) {
	    unset($htmlOptions[$opt]);
	}

	$options = $this->_optionsToString($options, array('multipleSeparator'));
	$callbacks = array('formatItem', 'formatMatch', 'formatResult', 'highlight');

	foreach ($callbacks as $callback) {
	    if (isset($options[$callback])) {
		$name = $callback;
		$code = $options[$callback];
		switch ($name) {
		    case 'formatResult':
			$options[$name] = "function(data, i, max) {" . $code . "}";
			break;
		    case 'highlight':
			$options[$name] = "function(data, search) {" . $code . "}";
			break;
		    default:
			$options[$name] = "function(row, i, max, term) {" . $code . "}";
			break;
		}
	    }
	}
	$options = $this->_buildOptions($options, $this->autoCompleteOptions);

	$text = $this->Form->text($field, $htmlOptions);
	$script = "{$var} $('#{$htmlOptions['id']}').autocomplete(";
	$script .= "{$options});";

	return "{$text}\n" . $this->Javascript->codeBlock($script);
    }

And here are the sample to use it in our application

echo $this->Ajax->autoComplete('Guest.search', array(
    'source' => array(
	'controller' => 'users',
	'action' => 'autoComplete',
	'prefix' => 'host'
    ),
));

Action code :

 /**
     * Auto Complete Action for Host
     *
     * Auto Complete action for host list of guests
     * also process the search
     */
    function host_autoComplete() {
	if (!empty($this->data)) {
	    $this->redirect(array(
		'controller' => 'users',
		'action' => 'view', $this->data['Guest']['id']
	    ));
	}
	$this->autoRender = false;
	$guests = $this->User->getGuests(array(
		    'host_id' => Configure::read('User.id'),
		    'conditions' => array(
			'OR' => array(
			    'User.name LIKE' => '%' . $_GET['term'] . '%',
			    'User.surname LIKE' => '%' . $_GET['term'] . '%'
			)
		    )
		));
	echo json_encode($this->User->autoComplete_encode($guests));
    }

Model method ( encode the data array to display fields that we want, in this example I am just showing firstname and surname )

  /**
     * autoComplete encode
     *
     * Parsing passed array and change it to consume-able
     * by autocomplete jQuery UI
     * @param array $data
     * @return json $data
     */
    function autoComplete_encode($postData = array()) {
	$temp = array();
	foreach ($postData as $user) {
	    array_push($temp, array(
		'id' => $user['User']['id'],
		'label' => $user['User']['name'].' '.$user['User']['surname'],
		'value' => $user['User']['name'],
	    ));
	}
	return $temp;
    }

Don’t forget to use $_GET['term'] to get data from autocomplete field and also encode the data to JSON so it can be displayed by jQuery UI.

Fixed static image path in Javascript using CakePHP

Today I was encountered a problem within the static path for images in my Javascript file. So this was a design that given by my friend Budi, and he using a Jquery slider plugin in his design. Here are the original Javascript file that he gave me :
Continue reading →

Upload file in CakePHP using Media Plugin

There are many solutions to handle file upload in PHP, one of the common solutions is to create a custom action that will check the type of the file, size, validate whether the file name already exists or not, and the last thing is moving the file using move_uploaded_file(). However, it doesn’t end when the files are in your server, after that you still need to write a function to delete the files, manipulate it if needed and so on.

I already tried several ways to handle upload file in CakePHP, from writing a private action in the app_controller and the last I write a component.

I can upload file, delete file, check the file type using my Upload Component, but I realize that there are many things missing in my component.

In searching for inspiration, I found CakePHP do have serveral plugins to handle File Upload and the features are beyond my component.

One of the plugin is Media Plugin by Davidpersson.

Using the plugin is quite easy, but the wiki and the CakeFest slide is not updated with the new configuration ( I am using v1.3alpha ), so you need to jumped in to the core and trying to understand the new configuration.

Basically the plugin consist of several behaviours :

  • Transfer
  • Polymorphic
  • Meta
  • Generator
  • Coupler

But in this post I will just cover the Transfer,Coupler and Meta behaviour because I only understand these behaviours. So lets go to the implementation part, here is my CakePHP and Media Plugin version :

  1. CakePHP 1.3.0
  2. Media Plugin 1.3 alpha

First you must create a table that has a ‘file’ field in it. Remember, the field must be named ‘file’ or the plugin won’t working. Here is the example with my application :

CREATE TABLE IF NOT EXISTS `photos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `file` varchar(255) NOT NULL,
  `dirname` varchar(255) NOT NULL,
  `basename` varchar(255) NOT NULL,
  `checksum` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;

The field that will be used by the plugin are file, dirname, basename, and checksum. But the three last fields is optional, so you can have it in your table or not (if you are using Coupler, and Meta behaviour you MUST add the there fields ). Next, bake the application ( I was using ‘cake bake’ command ).

After that grab the Media Plugin from the github and put it in the plugins folder of your application. Next you will need to include the plugin to your application, open your bootstrap.php / core.php and add this line in it :

require APP . 'plugins/media/config/core.php';

Then create the folder that will be used for storing the files. Go to your application folder in terminal and type this command ( ex: /var/www/sample ) :

cake media init

The command will ask whether you want to create the directories or not, this is the print out of my terminal :

rudy@rudy-laptop:~/www/dummy$ cake media init
---------------------------------------------------------------
Media Shell
---------------------------------------------------------------
Do you want to create missing media directories now?
[n] > y
/dummy/webroot/media/                              [OK  ]
/dummy/webroot/media/static/                       [OK  ]
/dummy/webroot/media/static/aud                    [OK  ]
/dummy/webroot/media/static/css                    [OK  ]
/dummy/webroot/media/static/doc                    [OK  ]
/dummy/webroot/media/static/gen                    [OK  ]
/dummy/webroot/media/static/ico                    [OK  ]
/dummy/webroot/media/static/img                    [OK  ]
/dummy/webroot/media/static/js                     [OK  ]
/dummy/webroot/media/static/txt                    [OK  ]
/dummy/webroot/media/static/vid                    [OK  ]
/dummy/webroot/media/transfer/                     [OK  ]
/dummy/webroot/media/transfer/aud                  [OK  ]
/dummy/webroot/media/transfer/css                  [OK  ]
/dummy/webroot/media/transfer/doc                  [OK  ]
/dummy/webroot/media/transfer/gen                  [OK  ]
/dummy/webroot/media/transfer/ico                  [OK  ]
/dummy/webroot/media/transfer/img                  [OK  ]
/dummy/webroot/media/transfer/js                   [OK  ]
/dummy/webroot/media/transfer/txt                  [OK  ]
/dummy/webroot/media/transfer/vid                  [OK  ]
/dummy/webroot/media/filter/                       [OK  ]

/dummy/webroot/media/transfer/.htaccess is not in your webroot.
Remember to set the correct permissions on transfer and filter directory.

Change the permission of the folder so that the webserver can write in it :

chown -R www-data webroot/media

Configure the ‘Photo’ model like this :

class Photo extends AppModel {
	var $name = 'Photo';
	var $displayField = 'title';
	var $actsAs = array('Media.Transfer','Media.Coupler','Media.Meta');
	var $validate = array(
		'file' => array(
			'mimeType' => array(
			'rule' => array('checkMimeType', false, array ( 'image/jpeg', 'image/png'))
		),
		'size' => array(
			'rule' => array('checkSize' , '5M')
		)
	));
}

As you can see, I added 3 behaviors ( Transfer, Coupler and Meta ). The transfer behavior is used for uploading, moving and validating the file. The coupler is for deleting the file ( it will automatically delete the file if you delete a record associated with it and also will automatically add the value in dirname and basename ), the last thing that it will do is adding the meta description to the table ( checksum ).

Edit the add.ctp and adding the ‘type’ => ‘file’ in the $this->Form->create and the $this->Form->input(‘file’) so the form can handle file upload. In the controller you don’t need to change anything because the behavior automatically handle the validation, the path and moving the file. this is my controller :

Photo->recursive = 0;
		$this->set('photos', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(sprintf(__('Invalid %s', true), 'photo'));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('photo', $this->Photo->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Photo->create();
			if ($this->Photo->saveAll($this->data)) {
				$this->Session->setFlash(sprintf(__('The %s has been saved', true), 'photo'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), 'photo'));
			}
		}
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(sprintf(__('Invalid %s', true), 'photo'));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Photo->save($this->data)) {
				$this->Session->setFlash(sprintf(__('The %s has been saved', true), 'photo'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), 'photo'));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Photo->read(null, $id);
		}
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s', true), 'photo'));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Photo->delete($id)) {
			$this->Session->setFlash(sprintf(__('%s deleted', true), 'Photo'));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(sprintf(__('%s was not deleted', true), 'Photo'));
		$this->redirect(array('action' => 'index'));
	}
}
?>

and this is my add view :

Form->create('Photo',array('type' => 'file'));?>
	Form->input('title');
		echo $this->Form->input('file',array('type' => 'file'));
	?>
Form->end(__('Submit', true));?>

Now you are ready to uploading files, deleting files, and validate them in the model ( for validation you can see the wiki in the github for complete validation ). That’s all :D

Git free revision control

Sambil nungguin compile e-texteditor yang entah kelar kapan gwa mo cerita-cerita dikit tentang mainan baru gwa, yaitu Git. Mengutip sedikit tentang Git dari wikipedia :

Git is a free distributed revision control, or software source code management project with an emphasis on being fast. Git was initially designed and developed by Linus Torvalds for Linux kernel development.

Yah jadi intinya Git adalah sebuah revision control yang biasa digunakan project-project open source untuk mendeteksi perubahan-perubahan yang dilakukan pada project mereka. Entah itu berupa perubahan codingan, hapus file, nambah file,dkk. Jadi jika kita bekerja dalam Team dan akan sangat membantu sekali menggunakan Git ini karena dapat mendeteksi apa aja perubahan-perubahan yang dilakukan programmer-programmer.

Sudah banyak project open source yang mengadaptasi Git ini, beberapanya adalah CakePHP dan Lithium. Jadi jika anda berniat untuk ikut memberikan kontribusi terhadap project open source disarankan untuk mempelajari Git ini.

Jadi apa yang membedakan Git dengan revision control yang lain seperti SVN, atau CVS ? jawabannya gwa juga ga tau pasti karena Git adalah revision control yang pertama kali gwa pelajari. Tapi dari yang gwa baca-baca satu perbedaan besarnya adalah dengan menggunakan Git kita dapat melakukan commit secara locally tanpa harus terkoneksi dengan internet.

Apakah itu commit ? itu semacam istilah yang menandakan anda telah selesai melakukan perubahan dan menyimpan perubahan-perubahan. Yah masih banyak istilah-istilah Git yang bakal anda pelajari

Selain itu hal yang gwa suka dari menggunakan Git adalah website Github. Github adalah sebuah aplikasi website yang dibangun menggunakan Ruby on Rails dan berfungsi sebagai repository dari Git, jadi dengan mendaftarkan diri ke Github kita dapat melakukan upload ke server Github dengan menggunakan perintah “git push”. Hal tersebut tentu saja membantu kita yang ingin bekerja secara sistematis, terkontrol dan tanpa harus menyiapkan server repository, aplikasi website buat memantaunya karena Github sudah menyediakan tracking yang dapat melihat hasil commit dari masing-masing invididu dalam team.

Yup kira-kira itu saja lah perkenalan Git yang baru gwa gunakan kurang lebih baru 2 minggu, mungkin nanti kalau gwa udah jago pake Git gwa bakal posting tutorialnya disini ( hore akhirnya bulan februari tulis blog ). Until next time….

Ruby on Rails in Kubuntu 9.04

Beberapa hari ini gwa disibukkan mencoba menginstall Ruby on Rails ( RoR ). Sebenarnya sudah cukup lama pengen coba-coba Ruby on Rails, tapi sekarang baru ada semangat sama ada waktu buat nyoba-nyoba.

Menginstall Ruby on Rails ini dapat dibilang cukup memakan banyak waktu dikarenakan gwa menghabiskan 1 harian HANYA untuk install Kubuntu doank ( gara2 cd rom yang ga jelas ).

Jadi setelah gwa berhasil menginstall kubuntu ( yang tentu saja gwa selesaikan dalam waktu 1 hari ) gwa mulai menginstall Ruby on Rails. Mungkin masih pada bingung sebenarnya Ruby on Rails itu apaan. Ruby on Rails itu adalah sebuah framework untuk pembuatan website yang dibuat dengan menggunakan bahasa Ruby.

Apa istimewanya ? Kok semua sekarang pada ngomong Ruby on Rails mulu ? Kalau yang setau gwa Ruby on Rails adalah framework yang pertama kali menerapkan konsep MVC ( Model – View – Controller ) yang banyak diadopsi oleh framework-framework lain ( CakePHP, CI, Symfony, Spring, dll ). Selain itu Twitter juga menggunakan Ruby on Rails sebagai platform utamanya ( walaupun ada performance issue ).

Yah jadi langsung aja kita mulai step-step menginstall Ruby on Rails. Langkah-langkahnya sebenarnya terbagi dalam beberapa bagian yaitu :

  1. Menginstall package yang dibutuhkan oleh Ruby on Rails
  2. Menginstall database server yang mau digunakan
  3. Menginstall Ruby, Rubygem, dan yang terakhir Rails

Kelihatannya gampang menginstall Ruby on Rails, tetapi karena banyaknya dependency terhadap package membuat kita harus sering compile ulang Ruby ( mungkin yang pakai apt-get lebih gampang, tetapi sekarang kita akan mencoba install from source ).

Berikut biodata dari Ruby yang akan kita install :

  1. ruby-1.8.7-p174
  2. rubygems-1.3.5
  3. rubygems-1.3.5

Jadi sejauh pengalaman saya, beberapa package yang harus diinstall terlebih dahulu ( di Kubuntu ya, kalau distro lain ga ikutan ) adalah:

  1. Zlib
  2. Openssl
  3. Mysql dev ( jika ingin menggunakan mysql )

Kalau mau install zlib di kubuntu tinggal ketik aja

sudo apt-get install zlib1g-dev

sementara untuk openssl ketik

sudo apt-get install libopenssl-ruby1.9
sudo apt-get install libssl-dev

untuk library openssl bisa disesuaikan dengan versi rubynya ( dan kalau mau gampang search aja di Software Management kubuntunya ). Setelah itu kita akan menginstall mysql-server ( karena gwa pakainya mysql ). Kalau misalnya anda tidak ingin menggunakan mysql juga tidak apa-apa, karena defaultnya ruby itu menggunakan sqllite.

untuk mysql saya menggunakan command ini

sudo apt-get install mysql-server

sementara untuk library dev mysqlnya gwa menggunakan Software Management( jadi gwa ga gitu ingat packagenya yang mana ). Setelah selesai install mysqlnya kita tinggal download aja source Ruby dari website Ruby on Rails yaitu di www.rubyonrails.org dan pilih menu download. Disana bakal ada tulisan Source: Compile it yourself, nah tinggal klik aja tulisan source nya dan anda sudah dapat sourcenya Ruby.

Langkah-langkahnya kira-kira begini :

  1. Selesai download copy aja file source Rubynya ke mana aja ( ex : /usr/local )
  2. Extract file source tadi ( tar xzvf rubygems-1.3.5.tgz ).
  3. kemudian masuk ke dalam folder yang sudah diextract tadi.
  4. Jalankan langkah untuk compile ( ./configure, make, dan terakhir adalah make install ).
  5. gwa sempat mencoba menggunakan ./configure && make && make install tapi hasilnya tidak berhasil ( jadi kalau ada yang mau coba silakan saja, gwa sih pakai cara manual, jalanin satu2 ).

Nah setelah itu harusnya Ruby kita sudah terinstall, coba jalankan perintah ini :

ruby -v atau ruby --version

Jgn pernah jalanin ruby -version karena akan muncul error message ( harus — ). Kalau sudah terinstall harusnya muncul tulisan seperti ini :

ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-linux]

Nah kalau sudah benar lanjut ke step selanjutnya, kalau gagal coba debugging sendiri aja ya ( googling gitu ). Selanjutnya kita akan menginstall RubyGems atau bisa disebut sebagai Package Managernya Ruby ( mirip apt-get tapi punyanya Ruby ). Langkah-langkahnya :

  1. Masuk lagi ke website Ruby on Rails bagian download, http://rubyonrails.org/download
  2. Cari bagian RubyGems dan pilih Download
  3. Untuk versi terserah pilih yang mana suka la, gwa mah ambil yang paling baru.
  4. Setelah download tinggal pindahin aja ke folder mana aja ( ex : /usr/local ).
  5. Extract lagi RubyGems nya ( tar xzvf rubygems-1.3.5.tgz )
  6. Masuk ke folder yang baru diextract tadi dan jalankan perintah ruby setup.rb
  7. Tunggu proses dan jika tidak terjadi error maka jalankan perintah gem help

Jika gem terinstall dengan benar maka harusnya muncul help tentang penggunaan gem. Sekarang kita akan menginstall rails, tetapi sebelum kita harus menginstall Rake.

gem install rake

Setelah selesai kita tinggal menginstall Rails dengan :

gem install rails

Selesai menginstall rails seharusnya semua langkah sudah selesai, kita tinggal mengetes apakah Ruby on Rails berjalan dengan baik. Masuk ke folder tempat dimana anda akan menyimpan file website anda nanti ( ex: /home/rudy/ruby ). Kemudian ketik perintah ini :

rails blog -d mysql

Dari perintah diatas kita akan membuat folder dengan nama blog dan menggunakan koneksi mysql ( kalau ga pakai -d mysql, secara otomatis ruby akan membuat konfigurasi menggunakan sqllite ).

Masuk ke dalam folder blog tersebut, dan masuk ke dalam folder config dan cari file database.yml, kira-kira isinya begini :

# MySQL.  Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
#   gem install mysql
# On Mac OS X:
#   sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql
# On Mac OS X Leopard:
#   sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
#       This sets the ARCHFLAGS environment variable to your native architecture
# On Windows:
#   gem install mysql
#       Choose the win32 build.
#       Install MySQL and put its /bin directory on your path.
#
# And be sure to use new-style password hashing:
#   http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
  adapter: mysql
  encoding: utf8
  reconnect: false
  database: blog_development
  pool: 5
  username: root
  password:
  host: localhost

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: mysql
  encoding: utf8
  reconnect: false
  database: blog_test
  pool: 5
  username: root
  password:
  host: localhost

production:
  adapter: mysql
  encoding: utf8
  reconnect: false
  database: blog_production
  pool: 5
  username: root
  password: 
  host: localhost

ubah username dan password sesuai dengan settingan mysql anda. Kemudian keluar dari folder config dan jalankan perintah ini :

rake db:create 

Jika benar maka database akan otomatis terbuat ( jika ada error message berarti ada package mysql yang belum terinstall dengan benar ). Lalu jalankan perintah ini lagi :

script/generate controller home index 

tunggu sampai proses generate selesai ( jika ada yang error, yah anda tau sendiri lah, berarti ada package yang kurang ). Trus jalanin lagi perintah untuk jalanin webservernya :

script/server 

Jika benar maka akan ada proses menjalankan web servernya ( jgn diclose terminalnya karena akan membuat web server tersebut mati ). Untuk mengakses aplikasi Ruby on Rails yang baru dibuat, masuk ke web browser anda dan ketik


http://localhost:3000/

Selamat, anda telah berhasil menginstall Ruby on Rails dan sekarang tinggal belajar configurasinya aja :D

Group select box di CakePHP

Grouping di dalam select box adalah hal yang gampang ketika kita menggunakan codingan php biasa, tetapi kalau sudah masuk ke dalam codingan CakePHP kita harus banyak membaca documentation untuk teknik2nya, tickets jika ada yang pernah menanyakan hal yang sama dan tentu saja API agar kita tahu fungsi dari method yang akan kita pakai.

Jadi sekarang kita akan membuat sebuah grouping dalam select box seperti dalam gambar di bawah ini :

CakePHP Group Select

CakePHP Group Select

Di dalam contoh diatas gwa menggunakan 3 buah table di antaranya table majors ( jurusan ), table faculties ( fakultas ) dan table levels ( untuk pembagian apakah dia D3/S1 ). Hal pertama yang harus kita lakukan adalah men-query isi table dari majors ( dalam hal ini gwa menggunakan ClassRegistry karena table majors tidak ada relation dengan controller gwa ) :

$majors = ClassRegistry::init("Major")->find("all");

atau kalau punya relation / berada dalam controller sendiri
$majors = $this->Major->find("all");

Kemudian kita akan menggabungkan hasil query tersebut dan menyusunnya menjadi array yang jika kita masukkan ke dalam form helper maka akan secara otomatis menjadi select box yang tergroup. Kita akan menggunakan bantuan Set::combine untuk melakukan hal tersebut. Berikut contoh codingannya :

$majorsCombine = Set::combine($majors, "{n}.Major.id", array("%s - %s",
"{n}.Level.name", "{n}.Major.name"), "{n}.Faculty.name"); 

untuk penjelasan parameternya dapat dilihat di API CakePHP : API CakePHP

sedikit penjelasan tentang parameter yang gwa gunakan yaitu :

  • $majorsCombine Nama variable penampung.
  • Set::combine Nama method yang kita gunakan.
  • $majors Sumber data kita
  • {n}.Major.id Path pertama atau biasanya nilai dari select box kita
  • array(‘%s – %s’,'{n}.Level.name’, ‘{n}.Major.name’) Kalau ini path kedua yang berfungsi sebagai label dari isi select box kita, jika dilihat itu isinya ada level dan major jadi nanti keluarnya ( S1 – Teknik Informatika )
  • {n}.Faculty.name’ ini nama groupnya

Selanjutnya tinggal digunakan saja di viewnya seperti ini :

select("nama-form",$majorsCombine,null,null,"-- Pilih Jurusan Pertama --"); ?>

Penjelasannya kira-kira begini :

  • $form->select ini form helper yang kita gunakan
  • nama-form nama form helper yang kita gunakan
  • $majorsCombine sumber data
  • null,null,’– Pilih Jurusan Pertama — parameter tambahan lagi

Semoga membantu, silakan dicoba.. kalau ga jalan, dicoba lagi, kalau ga jalan juga ya sudah terima nasih aja :D

Membuat image sebagai link di CakePHP

Mungkin kita pernah membuat sebuah gambar menjadi sebuah link seperti untuk banner registrasi atau banner untuk iklan dan sebagainya.

Jika cara biasanya atau konvesional maka kita tinggal membuat seperti ini :


Sementara dalam CakePHP ada cara yang lebih gampang atau mungkin bagi beberapa orang lebih susah, yaitu :

link($html->image('/images/btn-register.png'), array('controller' => 'users','action' => 'add'),array('escape' => false)) ?>

atau kira-kira susunannya seperti ini
link($html->image('path-ke-image), array('controller' => 'nama-controller','action' => 'nama-action'),array('escape' => false)) ?>

Jadi kita menggunakan 2 buah helper yaitu link dan image dimana helper dari image kita letakkan di dalam helper link. Jangan lupa untuk menambahkan attribute escape => false atau gambar yang ingin anda tampilkan tidak akan muncul. Semoga bermanfaat :D