6: Edit a record

Posted under » CakePHP on 12 Dec 2018

Our application can now save/add articles, but we can’t edit them. Lets rectify that now. Add the following action to your ArticlesController:

// in src/Controller/ArticlesController.php  Add method.
public function edit($slug)
  {
   $article = $this->Articles->findBySlug($slug)->firstOrFail();
   if ($this->request->is(['post', 'put'])) {
   $this->Articles->patchEntity($article, $this->request->getData());
   if ($this->Articles->save($article)) {
   $this->Flash->success(__('Your article has been updated.'));
   return $this->redirect(['action' => 'index']);
         }
   $this->Flash->error(__('Unable to update your article.'));
    }   
   $this->set('article', $article);
  } 

This action first ensures that the user has tried to access an existing record. If they haven’t passed in an $slug parameter, or the article does not exist, a NotFoundException will be thrown, and the CakePHP ErrorHandler will render the appropriate error page.

Next the action checks whether the request is either a POST or a PUT request. If it is, then we use the POST/PUT data to update our article entity by using the patchEntity() method.

Finally, we call save() set the appropriate flash message and either redirect or display validation errors.

The edit template should look like this:

<!-- File: src/Template/Articles/edit.ctp -->
<h1>Edit Article
<¿php
echo $this->Form->create($article);
echo $this->Form->control('user_id', ['type' => 'hidden']);
echo $this->Form->control('title');
echo $this->Form->control('body', ['rows' => '3']);
echo $this->Form->button(__('Save Article'));
echo $this->Form->end();
?>

This template outputs the edit form (with the values populated), along with any necessary validation error messages. You can now update your index view with links to edit specific articles:

<!-- File: src/Template/Articles/index.ctp (edit links added) -->
<h1>Articles
<p><?= $this->Html->link("Add Article", ['action' => 'add']) ?>
<table>
<tr>
<th>Title
<th>Created
<th>Action
</tr>
<!-- Here's where we iterate through our $articles query object, printing out article info -->
<¿php foreach ($articles as $article): ?>
<tr>
<td>
<?= $this->Html->link($article->title, ['action' => 'view', $article->slug]) ?>
</td>
<td>
<?= $article->created->format(DATE_RFC850) ?>
</td>
<td>
<?= $this->Html->link('Edit', ['action' => 'edit', $article->slug]) ?>
</td>
</tr>
<¿php endforeach; ?>
</table>

Next we learn how to do input validation.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data