cialis online pharmacy generic xenical cheap cialis online cialis generic viagra online in canada buy cheap levitra online cialis without a perscription order viagra uk no prescription flagyl cheap generic levitra buying viagra in the uk cheap viagra approved cialis deltasone online buy viagra online without prescription non prescription cialis buy orlistat uk buy cialis in india prednisone 60 mg female viagra online buy viagra without prescription celebrex prescriptions buy cialis canada best prices viagra alternative to prednisone cheapest generic levitra levitra 5mg cheap viagra cialis on line buy xenical without prescription online accutane canadian health care prednisone no prescreption viagra online generic female viagra europe buy cialis low price cheap india viagra

Bulk Record Update In Cakephp

In this tutorial I will demonstrate to you how to updating multiple record in cakephp. We are using cakephp 1.3.4 and jQuery 1.4. We’ll use jQuery to select the items which we will update. This behavior is similar as we see in gmail, where we can choose any items that we will update. To do this we need is a list of records (I’m using contact) inside a form with check boxes on each row and one checkbox on table header to select all rows. At the bottom of the table there are two buttons that is to remove and to move selected items into the trash.

The Database And Table

First, we create new database and create contact table.

[php]
CREATE DATABASE `cakephp`;
[/php]

[php]
CREATE TABLE `contacts` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(32) default NULL,
`email` varchar(32) default NULL,
`phone` varchar(16) default NULL,
`subject` varchar(128) default NULL,
`message` text,
`status` tinyint(1) default ‘1’,
`created` datetime default NULL,
`modified` datetime default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
[/php]

We use the status column to mark the status of contacts, if “0” its means as trash items.

The Model

[php]
/**file:app/models/contact.php*/
<?php
class Contact extends AppModel {
var $name = ‘Contact’;
var $displayField = ‘name’;
var $validate = array(
’email’ => array(
’email’ => array(
‘rule’ => array(’email’),
‘message’ => ‘Please fill your correct email’,
//’allowEmpty’ => false,
//’required’ => false,
//’last’ => false, // Stop validation after this rule
//’on’ => ‘create’, // Limit validation to ‘create’ or ‘update’ operations
),
),
);
}
?>
[/php]

In the model, we apply the email validation.

The Controller

[php]

/**file:app/controllers/contacts_controller.php*/

<?php
class ContactsController extends AppController {
var $name =’Contacts’;
var $helpers = array(‘Javascript’,’Html’,’Form’,’Ajax’,’Time’);

function index() {
$this->Contact->recursive = 0;
$this->set(‘contacts’, $this->paginate());
}

function view($id = null) {
if (!$id) {
$this->Session->setFlash(__(‘Invalid contact’, true));
$this->redirect(array(‘action’ => ‘index’));
}
$this->set(‘contact’, $this->Contact->read(null, $id));
}

function add() {
if (!empty($this->data)) {
$this->Contact->create();
if ($this->Contact->save($this->data)) {
$this->Session->setFlash(__(‘The contact has been saved’, true));
$this->redirect(array(‘action’ => ‘index’));
} else {
$this->Session->setFlash(__(‘The contact could not be saved. Please, try again.’, true));
}
}
}

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

function delete($id = null) {
if (!$id) {
$this->Session->setFlash(__(‘Invalid id for contact’, true));
$this->redirect(array(‘action’=>’index’));
}
if ($this->Contact->delete($id)) {
$this->Session->setFlash(__(‘Contact deleted’, true));
$this->redirect(array(‘action’=>’index’));
}
$this->Session->setFlash(__(‘Contact was not deleted’, true));
$this->redirect(array(‘action’ => ‘index’));
}
function admin_index() {
$this->Contact->recursive = 0;
$this->set(‘contacts’, $this->paginate(array(‘Contact.status’=>’1’)));
}

function admin_view($id = null) {
if (!$id) {
$this->Session->setFlash(__(‘Invalid contact’, true));
$this->redirect(array(‘action’ => ‘index’));
}
$this->set(‘contact’, $this->Contact->read(null, $id));
}

function admin_add() {
if (!empty($this->data)) {
$this->Contact->create();
if ($this->Contact->save($this->data)) {
$this->Session->setFlash(__(‘The contact has been saved’, true));
$this->redirect(array(‘action’ => ‘index’));
} else {
$this->Session->setFlash(__(‘The contact could not be saved. Please, try again.’, true));
}
}
}

function admin_edit($id = null) {
if (!$id && empty($this->data)) {
$this->Session->setFlash(__(‘Invalid contact’, true));
$this->redirect(array(‘action’ => ‘index’));
}
if (!empty($this->data)) {
if ($this->Contact->save($this->data)) {
$this->Session->setFlash(__(‘The contact has been saved’, true));
$this->redirect(array(‘action’ => ‘index’));
} else {
$this->Session->setFlash(__(‘The contact could not be saved. Please, try again.’, true));
}
}
if (empty($this->data)) {
$this->data = $this->Contact->read(null, $id);
}
}

function admin_delete($id = null) {
if (!$id) {
$this->Session->setFlash(__(‘Invalid id for contact’, true));
$this->redirect(array(‘action’=>’index’));
}
if ($this->Contact->delete($id)) {
$this->Session->setFlash(__(‘Contact deleted’, true));
$this->redirect(array(‘action’=>’index’));
}
$this->Session->setFlash(__(‘Contact was not deleted’, true));
$this->redirect(array(‘action’ => ‘index’));
}
function admin_process(){
$this->autoRender = false;
if(!empty($this->data)){
//debug($this->data);
foreach($this->data[‘Contact’][‘id’] as $id=>$value){
if($value==1){
$ids[]=$id;
}
}
switch($this->data[‘Contact’][‘actions’]){
case 0:
//Move to trash
if($this->Contact->updateAll(array(‘Contact.status’=>0), array(‘Contact.id’=>$ids))){
$this->Session->setFlash(__(‘Contact move to trash ‘, true));
$this->redirect(array(‘action’=>’index’));
}
break;
case 1:
if($this->Contact->deleteAll(array(‘Contact.id’=>$ids))){
$this->Session->setFlash(__(‘Contact deleted permanently’, true));
$this->redirect(array(‘action’=>’index’));
}
default:
//something went wrong!!
$this->Session->setFlash(__(‘Something went wrong, please try again.’, true));
$this->redirect(array(‘action’=>’index’));
}

}

}
}
?>
[/php]

In the admin index we will only display the data with status 1. In admin_process we checking what action we will do, if 0 (move to trash) that is to move data into the trash if 1, we will remove the data permanently.

The first thing our new function needs to do is create an array of ids That were the contactschecked, because CakePHP earnest add a hidden field for every check box.

The View

[php]

/**file:app/views/contact/admin_index.pctp*/

<div class="contacts index">
<h2><?php __(‘Contacts’);?></h2>
<?php echo $form->create(‘Contact’,array(‘action’=>’process’));?>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $form->checkbox(‘all’); ?></th>
<th><?php echo $this->Paginator->sort(‘name’);?></th>
<th><?php echo $this->Paginator->sort(’email’);?></th>
<th><?php echo $this->Paginator->sort(‘phone’);?></th>
<th><?php echo $this->Paginator->sort(‘subject’);?></th>
<th><?php echo $this->Paginator->sort(‘message’);?></th>
<th><?php echo $this->Paginator->sort(‘created’);?></th>
<th><?php echo $this->Paginator->sort(‘modified’);?></th>
<th class="actions"><?php __(‘Actions’);?></th>
</tr>
<?php
$i = 0;
foreach ($contacts as $contact):
$class = null;
if ($i++ % 2 == 0) {
$class = ‘ class="altrow"’;
}
?>
<tr<?php echo $class;?>>
<td><?php echo $form->checkbox(‘Contact.id.’.$contact[‘Contact’][‘id’]); ?></td>
<td><?php echo $contact[‘Contact’][‘name’]; ?>&nbsp;</td>
<td><?php echo $contact[‘Contact’][’email’]; ?>&nbsp;</td>
<td><?php echo $contact[‘Contact’][‘phone’]; ?>&nbsp;</td>
<td><?php echo $contact[‘Contact’][‘subject’]; ?>&nbsp;</td>
<td><?php echo substr(0,100,$contact[‘Contact’][‘message’]).".."; ?>&nbsp;</td>
<td><?php echo $contact[‘Contact’][‘created’]; ?>&nbsp;</td>
<td><?php echo $contact[‘Contact’][‘modified’]; ?>&nbsp;</td>
<td class="actions">
<?php echo $this->Html->link(__(‘View’, true), array(‘action’ => ‘view’, $contact[‘Contact’][‘id’])); ?>
<?php echo $this->Html->link(__(‘Edit’, true), array(‘action’ => ‘edit’, $contact[‘Contact’][‘id’])); ?>
<?php echo $this->Html->link(__(‘Delete’, true), array(‘action’ => ‘delete’, $contact[‘Contact’][‘id’]), null, sprintf(__(‘Are you sure you want to delete # %s?’, true), $contact[‘Contact’][‘id’])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php
echo $this->Form->input(‘actions’, array(‘options’=>array(‘Trash’,’Delete’)));
echo $form->end(‘Go’);
?>
<p>
<?php
echo $this->Paginator->counter(array(
‘format’ => __(‘Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%’, true)
));
?> </p>

<div class="paging">
<?php echo $this->Paginator->prev(‘<< ‘ . __(‘previous’, true), array(), null, array(‘class’=>’disabled’));?>
| <?php echo $this->Paginator->numbers();?>
|
<?php echo $this->Paginator->next(__(‘next’, true) . ‘ >>’, array(), null, array(‘class’ => ‘disabled’));?>
</div>
</div>
<div class="actions">
<h3><?php __(‘Actions’); ?></h3>
<ul>
<li><?php echo $this->Html->link(__(‘New Contact’, true), array(‘action’ => ‘add’)); ?></li>
</ul>
</div>
[/php]

The Javascript

Include jQuery and functions.js that perform check/uncheck item in your default view with the JavaScript helper.

[php]

/**file:app/views/layout/default.ctp*/

<?php
/**
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs.view.templates.layouts
* @since CakePHP(tm) v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php echo $this->Html->charset(); ?>
<title>
<?php __(‘CakePHP: the rapid development php framework:’); ?>
<?php echo $title_for_layout; ?>
</title>
<?php
echo $this->Html->meta(‘icon’);
echo $this->Html->css(‘cake.generic’);
echo $this->Html->script(array(‘https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js’,’function’));
echo $scripts_for_layout;

?>
</head>
<body>
<div id="container">
<div id="header">
<h1><?php echo $this->Html->link(__(‘CakePHP: the rapid development php framework’, true), ‘http://cakephp.org’); ?></h1>
</div>
<div id="content">

<?php echo $this->Session->flash(); ?>

<?php echo $content_for_layout; ?>

</div>
<div id="footer">
<?php echo $this->Html->link(
$this->Html->image(‘cake.power.gif’, array(‘alt’=> __(‘CakePHP: the rapid development php framework’, true), ‘border’ => ‘0’)),
‘http://www.cakephp.org/’,
array(‘target’ => ‘_blank’, ‘escape’ => false)
);
?>
</div>
</div>
<?php echo $this->element(‘sql_dump’); ?>
</body>
</html>
[/php]

Create a JavaScript file that performs the checked/unchecked check box.

[php]

/**file:app/webroot/js/function.js*/

$(document).ready(function()
{
$("#ContactAll").click(function()
{
var checked_status = this.checked;
//alert(checked_status);
$(‘input[type="checkbox"]’).each(function()
{
this.checked = checked_status;
});
});
});
[/php]

And that’s it! I hope you enjoyed this tutorial and find this article is useful for your cakephp project.

Related Posts

How to Show User IP Addresses in WordPress

eBag Toolkit

Twitter Cards PHP 1.1

Selfoss 2.4 – A Nice and Simple Alternative To Google Reader

1 Comment

  1. Motyar

    10.04.2010

    Wow really a great starter post for cake. Thanx.
    .-= Motyar´s last blog ..Create Image Placeholder with Php Placeholdit Clone Script =-.