CakePHP Tutorial Part 2: Add, Edit and Delete Operations

In our previous CakePHP 3.x Tutorial we have learned CakePHP framework installation, configuration, database creation, data listing and basic functionalities. Now we’ll be know about the CakePHP’s advanced functionality through creating a blog post application as an example.

Basic configuration and blog posts listing already have discussed in our previous tutorial. So before starting the advanced tutorial, you can see the CakePHP 3.x Tutorial for Beginners. In this advanced cakephp tutorial we’ll implement the functionality to add, edit, and delete blog posts.

cakephp-tutorial-blog-post-add-edit-delete-operations-by-codexworld

Adding Posts

Controller:
index() function fetch posts from the database and showing the posts. Now let’s allow for the adding of new posts.
For showing success and error message you should need to load the FlashComponent in the PostsController. At first create add() action in the PostsController. add() action render the view of post adding form and try to save the data using the Posts model if the HTTP method of the request was POST. This action also used for show the validation errors or other warnings.

<?php
// src/Controller/PostsController.php

namespace App\Controller;

class 
PostsController extends AppController
{
    public function 
initialize()
    {
        
parent::initialize();

        
$this->loadComponent('Flash'); // Include the FlashComponent
    
}
    
    public function 
index()
    {
        
$posts $this->Posts->find('all');
        
$this->set(compact('posts'));
    }
    
    public function 
add()
    {
        
$post $this->Posts->newEntity();
        if (
$this->request->is('post')) {
            
$post $this->Posts->patchEntity($post$this->request->data);
            
$post->created date("Y-m-d H:i:s");
            
$post->modified date("Y-m-d H:i:s");
            if (
$this->Posts->save($post)) {
                
$this->Flash->success(__('Your post has been saved.'));
                return 
$this->redirect(['action' => 'index']);
            }
            
$this->Flash->error(__('Unable to add your post.'));
        }
        
$this->set('post'$post);
    }
}

newEntity() is creating a new entity and passing it to the save() method in the Table class.
patchEntity() merge an array of raw data into an existing entity.

Model:
For data validation you need to create src/Model/Table/PostsTable.php model and define the validation rules. validationDefault() method tells CakePHP how to validate your data when the save method is called. We have specified here title and description should not be empty.

<?php
// src/Model/Table/PostsTable.php

namespace App\Model\Table;

use 
Cake\ORM\Table;
use 
Cake\Validation\Validator;

class 
PostsTable extends Table
{
    public function 
initialize(array $config)
    {
        
$this->addBehavior('Timestamp');
    }

    public function 
validationDefault(Validator $validator)
    {
        
$validator
            
->notEmpty('title')
            ->
notEmpty('description');

        return 
$validator;
    }
}

View:
Our src/Template/Posts/add.ctp view would be look like below. You’ll need to use CakePHP’s FormHelper to take advantage of the validation features.

<!-- File: src/Template/Posts/add.ctp -->

<h1>Add Blog Post</h1>
<?php
    
echo $this->Form->create($post);
    echo 
$this->Form->input('title');
    echo 
$this->Form->input('description', ['rows' => '3']);
    echo 
$this->Form->button(__('Save Post'));
    echo 
$this->Form->end();
?>
cakephp-tutorial-add-blog-post-by-codexworld

Now update the src/Template/Posts/index.ctp view with “Add New Post” link.

<?= $this->Html->link('Add New Post', ['action' => 'add']) ?>

Editing Posts

Controller:
edit() action first ensures that the user has passed an $id parameter to access an existing record. If they haven’t passed or the post does not exists, throw a NotFoundException.

public function edit($id null)
{
    
$post $this->Posts->get($id);
    if (
$this->request->is(['post','put'])) {
        
$post $this->Posts->patchEntity($post$this->request->data);
        
$post->modified date("Y-m-d H:i:s");
        if (
$this->Posts->save($post)) {
            
$this->Flash->success(__('Your post has been updated.'));
            return 
$this->redirect(['action' => 'index']);
        }
        
$this->Flash->error(__('Unable to update your post.'));
    }
    
$this->set('post'$post);
}

View:
src/Template/Posts/edit.ctp view might be look like this.

<!-- File: src/Template/Posts/edit.ctp -->

<h1>Edit Post</h1>
<?php
    
echo $this->Form->create($post);
    echo 
$this->Form->input('title');
    echo 
$this->Form->input('description', ['rows' => '3']);
    echo 
$this->Form->button(__('Save Post'));
    echo 
$this->Form->end();
?>
cakephp-tutorial-edit-blog-post-by-codexworld

Now update the src/Template/Posts/index.ctp view with “Edit Post” link.

<?= $this->Html->link('Edit', ['action' => 'edit'$post->id]) ?>

Deleting Posts

Controller:
Let’s allow user to delete posts by creating a delete() action in PostsController. delete() action deletes post specified by $id. After deleting the post user would be redirected to the index page.

public function delete($id)
{
    
$this->request->allowMethod(['post''delete']);

    
$post $this->Posts->get($id);
    if (
$this->Posts->delete($post)) {
        
$this->Flash->success(__('The post with id: {0} has been deleted.'h($id)));
        return 
$this->redirect(['action' => 'index']);
    }
}

Now update the src/Template/Posts/index.ctp view with Delte Post link. Also it will better if you show the confirmation message once the Delete link is clicked. $this->Form->postLink() creates a link with JavaScript confirm alert for preventing the accidental click.

<?= $this->Form->postLink(
    
'Delete',
    [
'action' => 'delete'$post->id],
    [
'confirm' => 'Are you sure?'])
?>

Testing

Go to the homepage page (http://localhost/cakephp/) => you can see posts list with working add, edit and delete links.

cakephp-tutorial-blog-post-listing-by-codexworld

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

19 Comments

  1. Abdul Raheem Said...
  2. Hoang Said...
  3. WebX Said...
  4. Sandeep Said...
  5. Huuquyasb Said...
  6. Kundan Said...
  7. Mandeep Said...
  8. Rajkishor Said...
    • CodexWorld Said...
  9. Amisha Said...
    • CodexWorld Said...
  10. Harshit Rastogi Said...
    • CodexWorld Said...
  11. SATHIYA Said...
    • CodexWorld Said...
  12. Công Ty Môi Trường Said...
  13. Amit Gupta Said...
    • CodexWorld Said...
  14. Sandeep Said...

Leave a reply

keyboard_double_arrow_up