CakePHP 4 Tutorial Part 2: Add, Edit and Delete Operations

Webs Codex
2 min readSep 24, 2020

--

The basic configuration and list of blog posts was explained in the previous tutorial. Before you start any advanced lessons, you can read the CakePHP 4.x Tutorial for Beginners. In this advanced Cakephp tutorial, we will implement the add, edit, and delete blog post functions.

The index() function fetch posts data from the database and displays the posts. Now let’s allow new posts to be added.

You need to load FlashComponent into PostsController to see success and error messages. First, create an add() action in PostsController. The add() action returns a form view for adding a post and tries to save data using the Posts model when the HTTP request method is POST. This action is also used to show validation errors or other warnings.

newEmptyEntity() creates a new object and passes it to the save() method in the Table class.

patchEntity() combines an array of raw data into an existing object.

templates/Posts/index.php

To validate data, you need to create a src/Model/Table/PostsTable.php model and define validation rules. The validationDefault () method tells CakePHP how your data should be validated when the write method is called. Here we have given the title and the description should not be empty.

Now update and Edit Posts

edit() method pass an $id parameter to access an existing data.

CakePHP 4 Tutorial Part 2: Add, Edit and Delete Operations

Originally published at https://www.webscodex.com on September 24, 2020.

--

--

Webs Codex
Webs Codex

Written by Webs Codex

Webs Codex is programming and web development blog

No responses yet