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.
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();
?>
Now update the src/Template/Posts/index.ctp
view with “Add New Post” link.
<?= $this->Html->link('Add New Post', ['action' => 'add']) ?>
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();
?>
Now update the src/Template/Posts/index.ctp
view with “Edit Post” link.
<?= $this->Html->link('Edit', ['action' => 'edit', $post->id]) ?>
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?'])
?>
Go to the homepage page (http://localhost/cakephp/
) => you can see posts list with working add, edit and delete links.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Thank you its works good.
Thank you so much!
Its really good tutorial Thanks CODEXWORLD, can you add tutorial build web application with JWT authentication with Cakephp 3.x.
Thanks in anticipation.
Please provide a login form tutorial using data validation
very good .. thanks @_@
Nice article .. Thanks
how we upload an image in cakephp 3.2 and download that image and store theire path in database……please help me….we are waiting for youe next topic
add new blog “multiple file uploading in cakephp” . we are waiting …..
@Rajkishor We’ll try to publish your requested tutorial soon. Please subscribe our newsletter to get notified.
hi i am getting and error on : $this->request->allowMethod([‘post’, ‘delete’]);
the error is: Method allowMethod does not exist
@Amisha Probably you are using old version of CakePHP.
allowMethod()
has newly added in version 2.5, you can useonlyAllow()
instead.how to get this table view!? do we have to write a new HTML for it!?
@Harshit Yes, you would need to write new HTML for table view listing in
src/Template/Posts/index.ctp
file. You can see the post listing tutorial in our previous post.Hi, Your tutorial is good and thank you for that. I have experienced with the CakePHP 2.3 . Now am started with the CakePHP 3, i have some problem with routing for Add, edit and Delete. Index page is loaded correctly, but I am trying to run the posts/add, it throws error like “/posts/add was not found on this server”.
Can you explain me the routing concept here.
Thanks in Advance…
@Sathiya
If you follow our tutorial, then you can access these URL without doing anything in routes. Only ensure that the root directory has a CakePHP’s default
.htaccess
file.Can you help me tutorial like system with CakePhp ?
I am not getting the table layout as show in the example.
And plz share some more example in cake php version 3.0 which cover a full tutorial on static website development.
that will be great for beginners like us
@Amit
We have already published CakePHP 3.x basic configuration and blog posts listing tutorial. Please read our CakePHP 3.x Tutorial for Beginners first.
You made my day!!!
Thanks