Ketan Patel

Multiple Images Upload in CakePHP


Multiple Images Upload in CakePHP

In this post we will see how to upload multiple images in cakephp.I am going to show the additional code for multiple image handling for both the action Add and Edit.What all you need is to simply copy paste in your application according to needs.

My table : posts
CREATE TABLE `posts` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`title` varchar(200) NOT NULL,
`body` text NOT NULL,
`image1` varchar(200), 
`image2` varchar(200), 
`image3` varchar(200),
PRIMARY KEY (`id`)
)

As you can see what are the fields of my 'posts' table.I have three fields for the images.Example: image1,image2,image3 etc.You may have different fields. Add the code given below for multiple image handling.

My uploaded images are stored in  app/webroot/img/uploads/posts  folder. I have one default image called 'no-icon.jpg' in the same folder which will be shown if the correct image is not available or in case of NULL value.

Controller : PostsController.php


Add Function

public function add() { 
  $this->Post->create();
  if ($this->request->is('post')) {

  // Image Handling code START //////
    for($i=1;$i<4;$i++)
    {
     if(empty($this->data['Post']['image'.$i]['name'])){
      unset($this->request->data['Post']['image'.$i]);
     }
     
      if(!empty($this->data['Post']['image'.$i]['name']))
      {
       $file=$this->data['Post']['image'.$i];
      $ary_ext=array('jpg','jpeg','gif','png'); //array of allowed extensions
      $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
      if(in_array($ext, $ary_ext))
      {
       move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads/posts/' . time().$file['name']);
       $this->request->data['Post']['image'.$i] = time().$file['name'];
      }
     }
     
    }
    // Image Handling code END //////   

    if ($this->Post->save($this->request->data)) 
    {
    $this->Session->setFlash('Your post has been saved.');
    $this->redirect(array('action' => 'index'));
   }
   else 
   {
    $this->Session->setFlash('Unable to add your post.');
   }
  }
 }


Edit Function
public function edit($id=null){
  if(!$id)
  {
   throw new NotFoundException(__('Invalid Post'));
  }
  $post=$this->Post->findById($id);
  if(!$post)
  {
   throw new NotFoundException(__('Invalid Post'));
   }
   
   if(!empty($this->data))
   {
    $this->Post->id=$id;
                                
    // Image Handling code START //////   
    for($i=1;$i<4;$i++)
    {
    if(empty($this->data['Post']['image'.$i]['name'])){
      unset($this->request->data['Post']['image'.$i]);
     }
     if(!empty($this->data['Post']['image'.$i]['name']))
     {
       if(file_exists("img/uploads/posts/".$this->data['Post']['hiddenimage'.$i])){
         unlink("img/uploads/posts/".$this->data['Post']['hiddenimage'.$i]);        
         }
      
      $file=$this->data['Post']['image'.$i];
      $ary_ext=array('jpg','jpeg','gif','png'); //array of allowed extensions
      $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
      
      if(in_array($ext, $ary_ext))
      {
       move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads/posts/' . time().$file['name']);
       $this->request->data['Post']['image'.$i] = time().$file['name'];
      }
     }
    }
            // Image Handling code END //////   
    
    if($this->Post->save($this->request->data))
    {
     $this->Session->setFlash('Your Post has been Updated');   
     $this->redirect(array('action'=>'index')); 
    }
    else
    {
     $this->Session->setFlash('Unable to update your post.');
    }
  }
  
  if(!$this->request->data){
   $this->request->data=$post;
  }
 }



Note : As of PHP 5.1, when called with no arguments, mktime() throws an E_STRICT notice: use the time() function instead.


I can't post all the code of view files so for that please Download the complete source code from the below link.

Download Full Source

Read More
Ketan Patel

Recursive in CakePHP

Recursive in CakePHP



Today we are going to learn about Recursive in CakePHP . Using this recursive property, Cake will know about the depth of the result that needs to be generated when find() and read() methods are used.It is needed to set the depth of the retrieval of records associated with a model data so we can limit how much data is fetched from the query in case of multi levels of associations between your models.

Read More
Ketan Patel

Dynamic Fields Validation in CakePHP

Dynamic Fields Validation in CakePHP



In this post we'll learn about dynamic fields validation. Generally simple validation is achieved by placing the validation rules in the model file.You can get the idea of how validation rules are written in model file by the example given below.

Read More
Ketan Patel

CRUD in CakePHP Part : 2

CRUD in CakePHP

In previous post we learnt about view and listing of the Users.In this post we'll learn about add,edit and delete operations.

Adding Users

To add a user record put the below function in our UsersController.php

public function add() {
        if ($this->request->is('post')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('User has been saved.'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('Unable to add User.'));
            }
        }
    }
Here we have to include the SessionComponent  and SessionHelper  in our controller.

public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');

Now its time to create view file for the add.So create a file add.ctp in /app/View/Users/
Our add view looks like.
<!-- File: /app/View/Users/add.ctp -->
<h1>Add User</h1>
<?php
echo $this->Form->create('User');
echo $this->Form->input('firstname');
echo $this->Form->input('lastname');
echo $this->Form->input('email');
echo $this->Form->input('message', array('rows' => '3'));
echo $this->Form->end('Save User');
?>

We used the FormHelper to generate the opening tag for an HTML form. $this->Form->create() will generates:

<form id="UserAddForm" method="post" action="/users/add">

The $this->Form->end()  generates a submit button.

Go back to update our /app/View/Users/index.ctp view file  for adding “Add User” link. Before the <table>, simply add the following line:

<?php echo $this->Html->link(
    'Add User',
    array('controller' => 'users', 'action' => 'add')
); ?>

Editing Users

Create a new edit() method in UsersController.php

public function edit($id = null) {
    if (!$id) {
        throw new NotFoundException(__('Invalid user'));
    }
    $user = $this->User->findById($id);
    if (!$user) {
        throw new NotFoundException(__('Invalid user'));
    }
    if ($this->request->is('post') || $this->request->is('put')) {
        $this->User->id = $id;
        if ($this->User->save($this->request->data)) {
            $this->Session->setFlash(__('User has been updated.'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('Unable to update User.'));
        }
    }
    if (!$this->request->data) {
        $this->request->data = $user;
    }
}



Create a view file for the edit method.

One thing to note here: CakePHP will assume that you are trying to edit a model if the ‘id’ field is present in the data array. If no ‘id’ is present, Cake will assume that you are trying to insert a new model when save() is called.

<!-- File: /app/View/Users/edit.ctp -->
<h1>Edit User</h1>
<?php
    echo $this->Form->create('User');
    echo $this->Form->input('firstname');
    echo $this->Form->input('lastname');
    echo $this->Form->input('email');
    echo $this->Form->input('message', array('rows' => '3'));
    echo $this->Form->input('id', array('type' => 'hidden'));
    echo $this->Form->end('Update User');

?>

To edit specific users, update your index view.

<?php echo $this->Html->link(
    'Add User',
    array('controller' => 'users', 'action' => 'add')
); ?>

<h1>Blog Users</h1>
<table>
    <tr>
        <th>Id</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email</th>
        <th>Message</th>
  <th>Action</th>
    </tr>
    <!-- Here is where we loop through our $users array, printing out user info -->

    <?php foreach ($users as $user): ?>
    <tr>
        <td><?php echo $user['User']['id']; ?></td>
        <td><?php echo $this->Html->link($user['User']['firstname'],
array('controller' => 'users', 'action' => 'view', $user['User']['id'])); ?></td>
        <td><?php echo $user['User']['lastname']; ?></td>
        <td><?php echo $user['User']['email']; ?></td>
        <td><?php echo $user['User']['message']; ?></td>
  <td><?php echo $this->Html->link('View', array('action' => 'view', $user['User']['id'])); ?>
  <?php echo $this->Html->link('Edit', array('action' => 'edit', $user['User']['id'])); ?>
       </td>
    </tr>
    <?php endforeach; ?>
    <?php unset($user); ?>
</table>

Deleting Users

Now create new function delete() in the UsersController:

public function delete($id) {
    if ($this->request->is('get')) {
        throw new MethodNotAllowedException();
    }
  if ($this->User->delete($id)) {
        $this->Session->setFlash(__('The user having id: %s has been deleted.', $id));
        $this->redirect(array('action' => 'index'));
    }
}


Add delete link in index.ctp file

<td>
    <?php echo $this->Form->postLink('Delete',array('action' => 'delete', $user['User']['id']),array('confirm' => 'Are you sure to delete?'));
?>
</td>


That's it..!! Your CRUD Application is Ready.

Download Demo

Read More
Ketan Patel

CRUD in CakePHP Part : 1

CRUD in CakePHP


In this post we will see how to create simple CRUD application in CakePHP.If you haven't setup cakephp yet then please read this post How to install CakePHP


Creating Users Database


Let’s set up the database for our blog. Right now, we’ll create a single table for our users. We will add few records of users in order to test. Simply run the SQL query given below into your DB:


/* Create our users table: */
CREATE TABLE users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(50),
    lastname VARCHAR(50),
    email VARCHAR(50),
    message TEXT
);


/* Then insert some users for testing: */
INSERT INTO users (firstname,lastname,email,message)
    VALUES ('Ricky', 'Astley', 'test1@test.com','Hello...!');
INSERT INTO users (firstname,lastname,email,message)
    VALUES ('John', 'clinton','test2@test.com','How are You...!' );
INSERT INTO users (firstname,lastname,email,message)
    VALUES ('Smith', 'Johnson', 'test3@test.com','I am Fine...!');


Create a User Model


CakePHP’s model class files resides in /app/Model, and the file we’ll be creating will be saved into /app/Model/User.php. The file should look like:


class User extends AppModel {

}

Create a User Controller


Now, we will create a controller of users.All the business logic for user interaction will happen in the controller. This new controller will be placed in a file called UsersController.php inside the /app/Controller directory. Basic controller should look like:


class UsersController extends AppController {
    public $helpers = array('Html', 'Form');
}


Now, lets add one action to our newly created controller. Actions represent a function in an application. For example, when you request : http://yoursite/users/index , users listings will be shown.code for that should look like:


class UsersController extends AppController {
    public $helpers = array('Html', 'Form');
    public function index() {
        $this->set('users', $this->User->find('all'));
    }
 }


Here note the use of set.It will pass the data that we get from the find(all) method to the view(we will create next) file. we can access the data of find(all) method using variable '$users' in the view file.


Creating User Views


Now create a view for the index action that we have created in above step.View files are stored in /app/View inside a folder named like controller(we  have to create a folder having name ‘Users’ in this case).


<!-- File: /app/View/Users/index.ctp -->
<h1>Blog Users</h1>
<table>
    <tr>
        <th>Id</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email</th>
        <th>Message</th>
    </tr>
    <!-- Here is where we loop through our $users array, printing out user info -->
    <?php foreach ($users as $user): ?>
    <tr>
        <td><?php echo $user['User']['id']; ?></td>
        <td><?php echo $user['User']['firstname'];?></td>     
        <td><?php echo $user['User']['lastname']; ?></td>
        <td><?php echo $user['User']['email']; ?></td>
        <td><?php echo $user['User']['message']; ?></td>
    </tr>
    <?php endforeach; ?>
    <?php unset($user); ?>
</table>



Now go to http://yoursite/users/index. You'll see listing of users, correctly formatted with the title and table listing of the users.


Now what we are going to do is when we click on any particular record it will display all the information of that record.So for that first of all create a new action or you can say it as a function in our controller.


public function view($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Invalid user'));
        }

        $user = $this->User->findById($id);
        if (!$user) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $user);
    }



Here we have used findById() method because we want to display the information for that particular record not for all the records.As we have used $users variable in the index method same here we are using $user variable by using which we can get the data returned by the findById method in view file.


Now create the view for our new ‘view’ action and place it in /app/View/Users/view.ctp

<!-- File: /app/View/Users/view.ctp -->
<h1>First Name:<?php echo h($user['User']['firstname']); ?></h1>
<h1>Last Name: <?php echo $user['User']['lastname'];?></h1>
<h1>Email:<?php echo h($user['User']['email']); ?></h1>
<h1>Message:<?php echo h($user['User']['message']); ?></h1>


To Verify that this is working, click on the links at /users/index or you can manually request a user by going www.example.com/users/view/1.(here 1 is the id of that user.)


We will see the Add,Edit and Delete Functionality in Next Post : CakePHP CRUD Part : 2

Download Demo

Read More
Ketan Patel

MySQL Event Scheduler



Read More