CakePHP Dynamic Input And saveAssociated

Dynamic input is very useful for any project that required dynamic number of inputs for example student can register many subjects and each subject has its own grades. How many subjects and grades input that we as developer should prepare? One student maybe registers one subject or more. Using the dynamic input concept can solve the problem.

Let assume that we have the table set as below:


In add new student page, developer need to create an input for grades as shown below:

    <legend><?php echo __('Grades');?></legend>
		<table cellpadding="0" cellspacing="0" class="table table-striped" id="grade-table">
		<?php if (!empty($this->request->data['Grade'])) :?>
					<?php for ($key = 0; $key < count($this->request->data['Grade']); $key++) :?>
						<?php echo $this->element('grades', array('key' => $key));?>
					<?php endfor;?>
				<?php endif;?>
                <td colspan="2"></td>
                <td class="actions">
                    <a href="#" class="add btn btn-success btn-xs">Add grade</a>

<script id="grade-template" type="text/x-underscore-template">
    <?php echo $this->element('grades');?>

Next, create new file known as grades.ctp in …/View/Elements. It should contain these codes:

$key = isset($key) ? $key : '<%= key %>';
        <?php echo $this->Form->hidden("Grade.{$key}.id") ?>
        <?php echo $this->Form->text("Grade.{$key}.subject"); ?>
        <?php echo $this->Form->select("Grade.{$key}.grade", array(
            'A+' => 'A+',
            'A' => 'A',
            'B+' => 'B+',
            'B' => 'B',
            'C+' => 'C+',
            'C' => 'C',
            'D' => 'D',
            'E' => 'E',
            'F' => 'F'
        ), array(
            'empty' => '-- Select grade --'
        )); ?>
    <td class="actions">
		<a href="#" class="remove btn btn-danger btn-xs">Remove grade</a>

Load the underscore.js CDN at the beginning of the add new student page as shown below:

<?php echo $this->Html->script(array(
)); ?>

If your CakePHP package does not include jQuery, please add the following code to call the jQuery CDN with underscore CDN as shown:

<?php echo $this->Html->script(array(
)); ?>

Add the following code to create an event handler at the end of the add new student page.

$(document).ready(function() {
        gradeTable = $('#grade-table'),
        gradeBody = gradeTable.find('tbody'),
        gradeTemplate = _.template($('#grade-template').remove().text()),
        numberRows = gradeTable.find('tbody > tr').length;

        .on('click', 'a.add', function(e) {

            $(gradeTemplate({key: numberRows++}))
        .on('click', 'a.remove', function(e) {

                .fadeOut('fast', function() {

        if (numberRows === 0) {

In your student controller, use saveAssociated as follows (refer line no 4):

public function add() {
	if ($this->request->is('post')) {
		if ($this->Student->saveAssociated($this->request->data)) {
			$this->Session->setFlash(__('The student has been saved.'), 'default', array('class' => 'alert alert-success'));
			return $this->redirect(array('action' => 'index'));
		} else {
			$this->Session->setFlash(__('The students could not be saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));

Figure 1: Dynamic input in student registration (add.ctp) page

Figure 2: View Dynamic input in view.ctp page