طبقه بندی موضوعی

Dynamic select box with CakePHP 2.0

پنجشنبه, ۱۶ آذر ۱۳۹۱، ۰۴:۰۸ ب.ظ

I wanted some auto populating Select boxes in a site I was creating so that when I changed a Category the Subcategories would automatically update. CakePHP can do this pretty easily but it is let down by the documentation as there are no examples.

Initially I came up with a version that wrote JSON into a JavaScript variable in the page and then used jQuery to achieve the updating of select elements but I wanted to do this the Cake way which uses AJAX and as little code as possible.

Here is a simplified solution to demonstrate how it can be done.

This assumes a new CakePHP site already configured with a database connection. I used CakePHP 2.0.3 but this may also work with 1.3 (?)

1. Models

We need 3 associated tables

CREATE TABLE `categories` (
  PRIMARY KEY (`id`)
INSERT INTO `categories` (`id`, `name`)
CREATE TABLE `posts` (
  `subcategory_id` INT(10) UNSIGNED DEFAULT NULL,
  PRIMARY KEY (`id`)
INSERT INTO `posts` (`id`, `title`, `subcategory_id`)
	(1,'The title',1),
	(2,'A title once again',4),
	(3,'Title strikes back',7);
CREATE TABLE `subcategories` (
  `category_id` INT(10) UNSIGNED DEFAULT NULL,
  PRIMARY KEY (`id`)
INSERT INTO `subcategories` (`id`, `category_id`, `name`)

Bake the 3 Models for these and allow CakePHP to define model associations for you.

2. Controllers

Bake a Controller for the Post Model with the default CRUD actions.

While you are at it you will also need to bake the CRUD Views for the Post Controller.

If you browse to the posts index page now you can view the data.
In this example I will add the Category and Subcategory select lists to the Add view, so now we need to change this so that the selection in the second list changes according to the selection in the first list.
This will be done via the Js Helper so make it available at the top of the Posts controller (after the Class declaration) with:

public $helpers = array('Js');

You need a Subcategories Controller with a single action to provide the data via AJAX:

App::uses('AppController', 'Controller');
class SubcategoriesController extends AppController {
	public function getByCategory() {
		$category_id = $this->request->data['Post']['category_id'];
		$subcategories = $this->Subcategory->find('list', array(
			'conditions' => array('Subcategory.category_id' => $category_id),
			'recursive' => -1
		$this->layout = 'ajax';


The view is a very simple AJAX view that renders the option tags that go within the select tag.

<!-- file path View/Subcategories/get_by_category.ctp -->
<?php foreach ($subcategories as $key => $value): ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php endforeach; ?>

4. Putting it all together

In the Post Add view, file path: View/Posts/add.ctp we can finally add the Js methods that make the dynamic updating happen. This is the cryptic bit that I struggled with for a few hours as although the CakePHP documentation outlines all the options there are not any complete examples.
Firstly add a categories select element to the form (and change the order of the elements):

	echo $this->Form->input('category_id');
	echo $this->Form->input('subcategory_id');
	echo $this->Form->input('title');

Add the following code to the bottom of the view, this uses the Js Helper to create the necessary jQuery to perform the updating:

		), array(
		'async' => true,
		'method' => 'post',
		'data'=> $this->Js->serializeForm(array(
			'isForm' => true,
			'inline' => true

This is saying – watch the HTML element with Id PostCategoryId for a change. When it changes update the HTML element with Id PostSubcategoryId with the response from subcategories/GetByCategory, the data option is used to send the current value from the initial select element.

Before you leap to test this you need to make changes to the default layout to include jQuery and provide a place for your scripts to be written out.

// file path View/Layouts/default.ctp
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
	<?php echo $this->Html->charset(); ?>
		<?php echo $title_for_layout; ?>
		echo $this->Html->meta('icon');
		echo $this->Html->css('cake.generic');
	<div id="container">
		<div id="header">
			<h1>Dynamic Select Box Demonstration</h1>
		<div id="content">
			<?php echo $this->Session->flash(); ?>
			<?php echo $content_for_layout; ?>
		<div id="footer">
	<?php echo $this->element('sql_dump'); ?>
	<script type="text/javascript" src=""></script>
	<!-- scripts_for_layout -->
	<?php echo $scripts_for_layout; ?>
	<!-- Js writeBuffer -->
	if (class_exists('JsHelper') && method_exists($this->Js, 'writeBuffer')) echo $this->Js->writeBuffer();
	// Writes cached scripts

Now you can test the application. On changing the category select list, the subcategory one will automatically update to show the relevant options.

نظرات  (۰)

هیچ نظری هنوز ثبت نشده است

ارسال نظر

ارسال نظر آزاد است، اما اگر قبلا در بیان ثبت نام کرده اید می توانید ابتدا وارد شوید.
شما میتوانید از این تگهای html استفاده کنید:
<b> یا <strong>، <em> یا <i>، <u>، <strike> یا <s>، <sup>، <sub>، <blockquote>، <code>، <pre>، <hr>، <br>، <p>، <a href="" title="">، <span style="">، <div align="">
تجدید کد امنیتی