Showing posts with label CakePHP. Show all posts
Showing posts with label CakePHP. Show all posts
Ketan Patel

Generate Previous Next Posts Link in CakePHP



There are many methods for retrieving your data in cakephp varying from simple find all to complex joins. CakePHP has many useful find type which makes the data retrieval process very easy without writing manual queries to fetch the data.
Read More
Ketan Patel

Implementing Welcome Popup in CakePHP Part : 2

This post is the second part of my previous article Implementing Welcome Popup in CakePHP. As I told you we'll add some more feature in the simple popup, so in this post what we are going to add is color fields for dynamic background, font color in popup and some route related stuff.
Read More
Ketan Patel

Custom Flash Messages in CakePHP

custom-flash-messages-in-cakephp




Notifying user with message when any action happen is very common idea in any application. In this post we'll discuss about the flash messages in cakephp. How to customize the cakephp default flash messages.

Read More
Ketan Patel

How to Integrate Color Picker in CakePHP

Credit : Flickr


In many applications you might need to have color code as an input. For such case its recommended to have any color picker instead of plain input. There are many jquery plugins available for color picker. In this tutorial we'll see how to integrate color picker in CakePHP. Here we are going to use Farbtastic jquery color picker.

Read More
Ketan Patel

Implementing Welcome Popup in CakePHP

This post has been moved to new site domain: php-dev-zone.com click here to read it
Read More
Ketan Patel

Ajax Call Validation in CakePHP

ajax call validation in cakephp



For any application, validation of user input is very important job. By doing so we make sure that the data in a model conforms to the business rules defined for the application. Simple examples for such validation rules can be email, alphanumeric, min-max value etc.

In this tutorial we're going to learn how to validate the ajax call in CakePHP. This post assumes that you know the basics of model validation rules.If not then i would suggest you to follow our Cakephp Tutorial Series to make the concept clear.

Read More
Ketan Patel

Upload and Download PDF File in CakePHP

In this tutorial we'll learn about how to upload, view and download pdf file in CakePHP.In my previous post on Multiple Image upload in CakePHP you learn about the basics of file upload, in this post we'll see some more CakePHP concepts regarding the file upload.


Upload and Download PDF file in Cakephp

Read More
Ketan Patel

Difference between Required and notEmpty in CakePHP


Difference between required and notEmpty in CakePHP



In cakephp,various validations rules are used to validate your forms like required, min length, maxlength etc.Such validation rules makes form handling much easier. But the thing we are going to discuss here is the difference between required and nonEmpty() rules. The use of both is quite easy to understand, but the interesting thing is difference between them.


Read More
Ketan Patel

Search with Pagination Using Session in CakePHP


Search With Pagination in CakePHP


In this post i would like to show you how you can handle search forms while preventing pagination using session in cakephp.The basic idea is to set the entered search data in a session and add that as a condition for finding the records.

Read More
Ketan Patel

Creating RSS Feed in CakePHP


rss feed in cakephp



In this post we will learn how to create rss feed in cakephp.This is very easy tutorial to understand and implement.We are going to use cakephp simple blog tutorial here.


Read More
Ketan Patel

CakePHP Tips

cakephp  tips




If you are learning CakePHP then you should know some basic & small snippets that are very useful while developing app with CakePHP.This post contains such small but very useful cakephp tips.

Read More
Ketan Patel

How to Log Errors in Database in CakePHP

How to log Errors in Database in CakePHP



In this post we're going to learn how to log errors in the database in cakephp.Before moving direct on the topic lets clear the default behaviour of cakephp's error logging.

Read More
Ketan Patel

How to Pass the Controller Data to JS File in CakePHP

Sometimes it requires to pass the data of the controller file to the javascript files or the view files in cakephp. CakePHP has one inbuilt method called “Controller::set() ”for passing the variable from controller to view. We will use this method in this tutorial.

Read More
Ketan Patel

Export Data into Excel or CSV file in CakePHP

Once I was working on cakePHP demo project in which I need to export the data to CSV format. As it was specific to cakephp I have to find the way how to accomplish this. So for that I googled and found one easy and effective solution that I am going to share with you. I hope you find it helpful.

Export Data into CSV file in Cakephp



Read More
Ketan Patel

How to Generate Barcode image in CakePHP


How to Generate Barcode image in Cakephp




In this easy and tutorial we are going to learn how to generate Barcode image in CakePHP. In CakePHP we have Barcode Helper class to fulfill this. This helper can generate different Barcodes. This Helper has following features.

Read More
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="/https/php-dev-zone.blogspot.com/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', '[email protected]','Hello...!');
INSERT INTO users (firstname,lastname,email,message)
    VALUES ('John', 'clinton','[email protected]','How are You...!' );
INSERT INTO users (firstname,lastname,email,message)
    VALUES ('Smith', 'Johnson', '[email protected]','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