Now that we have an overview and a view, we’re going to create the possibility to create a new post.
First, open the Blog module
routes.config.php. We’re creating the route first with the following code:
'add' => [ //routeName: blog/add //route: /blog/add 'type' => 'Literal', 'may_terminate' => true, 'options' => [ 'route' => '/add', 'defaults' => [ 'module' => 'Blog', 'controller' => 'Blog\\Controller\\Post', 'action' => 'add', ], ], ],
Add this underneath the
blog/view route. You might’ve noticed that here we’re using a Literal type. This is because this route will not have any child routes and does not accept parameters. Therefore the entire route will “literally” be the same as the defined route.
Next up, the view. Open up
add.phtml and copy in the following:
/** @var Blog\Form\PostForm $form */ ?> <section> <?php $form->prepare() ?> <?= $this->form()->openTag($form) ?> <?= $this->formRow($form->get('csrf')) ?> <?= $this->formRow($form->get('id')) ?> <?= $this->formRow($form->get('title')) ?> <?= $this->formRow($form->get('body')) ?> <?= $this->formRow($form->get('submit')) ?> <?= $this->form()->closeTag($form) ?> </section>
Forms are new to this tutorial, so a quick explanation. Zend Framework contains a few under the hood magical things to help us create forms in as easy a manner as possible. However, it doesn’t contain everything, we’ll be fixing what we need shortly.
In the code above you can see several functions defined. The
$form->prepare() function takes whatever information is available in the view for the
$formvariable and prepares it for printing. The form variable should be ready for use by the time execution reaches the view, so if you wish to do any changes you should do this in the Controller or the form itself. We’ll be creating our own
Form instantiation later.
$this->form()->openTag() is a Zend ViewHelper function that prints the opening tag, the HTML
<form> element with all attributes as defined in
$this->formRow() creates a new row of a form. A single row is its own
<div> element with a
$this->formRow() takes the argument of type
Element which is a Zend defined form element.
Last is the
$this->form()->closeTag(), which is nothing more exiting as printing the
</form> closing tag.
If you’ve noticed the warning your editor should’ve given you and have wondered about it until now, we’re now going to fix that. You see that that in the view we’ve set the Annotation that the
$form variable contains a single instance of the
PostForm class. However, it doesn’t exist, so lets fix that next.