Thursday, May 6, 2010

How to Create Multiple AJAX Forms on Same Page in CakePHP

Settings: Say, your posts/index.ctp page displays the latest ten posts. You want to allow user to rate each post.
Requirement: You MUST have a Post Model and a Comment Model.
In your respective view file: /app/view/posts/view.ctp
Type:

$i = 0; // a counter to create new divs

foreach ($posts as $post) :

// Code to display your post title, body etc.
// Now our comment form for each post

$i++;

$new_comment = 'new_comment_'.$i ; // for comment div id
$form_id = 'form_id_'.$i; // for form id

echo '<div id="'.  $new_comment .'"</div>';

echo $ajax->form(array('type' => 'post', 'options' => array(
'model'=>'Post', 
'update'=>$new_comment,
 'url'=>array('controller'=>'comments','action'=>'add'),
 'id'=>$form_id,'class'=>'CommentForm')
                                        ));

echo $form->input('comment',array('label'=>'Write your comment','type'=>'textarea', 'cols'=>'60','rows'=>'4'));

echo $form->end('Submit'); // close the form

// now close div
echo '</div>';
endforeach;

- - - - - - - - -
The idea is to create unique div to position each form and creating unique id for each form.

I created this post just before leaving for my office on the fly. Let me know if it helps.