A free and open-source book on ZF3 for beginners

12.13. Implementing Admin Page

Admin page of the Blog sample web application contains the list of all blog posts (either published or drafts), and allows to view, edit and delete posts.

To implement this page, add the adminAction() action method to the PostController class, as follows:


class PostController extends AbstractActionController 
   * This "admin" action displays the Manage Posts page. This page contains
   * the list of posts with an ability to edit/delete any post.
  public function adminAction()
    // Get posts
    $posts = $this->entityManager->getRepository(Post::class)
               ->findBy([], ['dateCreated'=>'DESC']);
    // Render the view template
    return new ViewModel([
            'posts' => $posts,
            'postManager' => $this->postManager

We will also need to show a post status in text form ('Draft' or 'Published'). Conversion of integer post status to string can be implemented in the getPostStatusAsString() method of PostManager service. Add the getPostStatusAsString() method to PostManager class as follows:

 * Returns status as a string.
public function getPostStatusAsString($post) 
    switch ($post->getStatus()) {
        case Post::STATUS_DRAFT: return 'Draft';
        case Post::STATUS_PUBLISHED: return 'Published';
    return 'Unknown';

Finally, add the corresponding view template file admin.phtml to the application/post directory under module's view directory:

<h1>Manage Posts</h1>

<a class="btn btn-default" href="
    <?= $this->url('posts', ['action'=>'add']); ?>">
    New Post

<table class="table table-striped">

        <th>Post Title</th>
        <th>Date Created</th>
    <?php foreach ($posts as $post): ?>
        <td><?= $this->escapeHtml($post->getId()); ?></td>
            <a href="<?= $this->url('posts', ['action'=>'view', 'id'=>$post->getId()]); ?>">
                <?= $this->escapeHtml($post->getTitle()); ?>
        <td><?= $this->escapeHtml($post->getDateCreated()); ?></td>        
        <td><?= $this->escapeHtml($postManager->getPostStatusAsString($post)); ?></td>
            <a class="btn btn-info" href="<?= $this->url('posts', 
                    ['action'=>'edit', 'id'=>$post->getId()]); ?>">
                <span class="glyphicon glyphicon-pencil" ></span> Edit
            <a class="btn btn-danger" href="<?= $this->url('posts',
                    ['action'=>'delete', 'id'=>$post->getId()]); ?>">
                <span class="glyphicon glyphicon-remove"></span> Delete
    <?php endforeach; ?>   

Now, if you open the URL http://localhost/posts/admin in web browser's navigation bar, you should be able to see the page like in figure 12.10 below:

Figure 12.10. Blog Admin page Figure 12.10. Blog Admin page