Editing and Deleting Data
In the previous chapter we've come to learn how we can use the zend-form and zend-db components for creating new data-sets. This chapter will focus on finalizing the CRUD functionality by introducing the concepts for editing anddeleting data.
Binding Objects to Forms
The one fundamental difference between our "add post" and "edit post" forms is the existence of data. This means we need to find a way to get data from our repository into the form. Luckily, zend-form provides this via a data-bindingfeature.
In order to use this feature, you will need to retrieve a Post
instance, and bind it to the form. To do this, we will need to:
- Add a dependency in our
WriteController
on ourPostRepositoryInterface
, from which we will retrieve ourPost
. - Add a new method to our
WriteController
,editAction()
, that will retrieve aPost
, bind it to the form, and either display the form or process it. - Update our
WriteControllerFactory
to inject thePostRepositoryInterface
.
We'll begin by updating the WriteController
:
- We will import the
PostRepositoryInterface
. - We will add a property for storing the
PostRepositoryInterface
. - We will update the constructor to accept the
PostRepositoryInterface
. - We will add the
editAction()
implementation.
The final result will look like the following:
<?php
// In module/Blog/src/Controller/WriteController.php:
namespace BlogController;
use BlogFormPostForm;
use BlogModelPost;
use BlogModelPostCommandInterface;
use BlogModelPostRepositoryInterface;
use InvalidArgumentException;
use ZendMvcControllerAbstractActionController;
use ZendViewModelViewModel;
class WriteController extends AbstractActionController
{
/**
* @var PostCommandInterface
*/
private $command;
/**
* @var PostForm
*/
private $form;
/**
* @var PostRepositoryInterface
*/
private $repository;
/**
* @param PostCommandInterface $command
* @param PostForm $form
* @param PostRepositoryInterface $repository
*/
public function __construct(
PostCommandInterface $command,
PostForm $form,
PostRepositoryInterface $repository
) {
$this->command = $command;
$this->form = $form;
$this->repository = $repository;
}
public function addAction()
{
$request = $this->getRequest();
$viewModel = new ViewModel(['form' => $this->form]);
if (! $request->isPost()) {
return $viewModel;
}
$this->form->setData($request->getPost());
if (! $this->form->isValid()) {
return $viewModel;
}
$post = $this->form->getData();
try {
$post = $this->command->insertPost($post);
} catch (Exception $ex) {
// An exception occurred; we may want to log this later and/or
// report it to the user. For now, we'll just re-throw.
throw $ex;
}
return $this->redirect()->toRoute(
'blog/detail',
['id' => $post->getId()]
);
}
public function editAction(