I am learning Zend 2 and have an issue i cannot seem to get around. Im sure it is something simple but i cannot pinpoint it. What i am trying to do is list records by state_id and also view a record from the list. Showing only one of the views. When i bring up /Blog/view/1 I get a message that says: Could not find row 0. This shows up with the current link and if i take the /1 off. So it is not even looking at the record number. I suspect it may be in routing but not sure. thanks This is what i have:
Module.config
'router' => array(
'routes' => array(
'blog' => array(
'type' => 'Literal',
'options' => array(
'route' => '/Blog',
'defaults' => array (
'module' => 'Blog',
'controller' => 'BlogController',
'action' => 'index',
), // defaults end
), // options end
'may_terminate' => true,
'child_routes' => array(
'list' => array(
'type' => 'segment',
'options' => array(
'route' => '/list[/:state_id]',
'defaults' => array (
'action' => 'list',
), //defaults end
'constraints' => array(
'state_id' => '[0-9]+',
) // constraints end
), // options end
), // view end
'view' => array(
'type' => 'segment',
'options' => array(
'route' => '/view[/:post_id]',
'defaults' => array(
'action' => 'view',
), // defaults end
'constraints' => array(
'post_id' => '[0-9]+',
) // constraints end
), // options end
), // post end
) // child route end
), // blog end
) // routes end
) // router end
); // return array end
Model:PostTable.php
public function getPosts($post_id)
{
$post_id = (int) $post_id;
$rowset = $this->tableGateway->select(array('post_id' => $post_id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $post_id");
}
return $row;
}
View:
<h1><?php echo $this->escapeHtml($title); ?></h1>
<table class="table">
<tr>
<th>Title</th>
<th>View</th>
<th>Comments</th>
<th>Post Date</th>
</tr>
<?php foreach ($list as $posts) : ?>
<tr>
<td><?php echo $this->escapeHtml($posts->post_title);?></td>
<td><?php echo $this->escapeHtml($posts->num_views);?></td>
<td><?php echo $this->escapeHtml($posts->num_comments);?></td>
<td><?php echo $this->escapeHtml($posts->post_date);?></td>
</tr>
<?php endforeach; ?>
Edit: 06/06/2016 Added View Action.
public function viewAction()
{
return new ViewModel(array(
'list' => $this->getPostsTable()->getPosts(),
));
}
Also here is the getPostTable Action:
public function getPostsTable()
{
if (!$this->postsTable) {
$sm = $this->getServiceLocator();
$this->postsTable = $sm->get('Blog\Model\PostsTable');
}
return $this->postsTable;
}
You need to provide the post ID into the getPosts()
method in the controller. The following is according to your PostTable
's getPosts()
method.
public function viewAction()
{
// Get the post ID from the route, /Blog/view/1
$post_id = $this->params()->fromRoute('post_id');
$list = $this->getPostsTable()->getPosts($post_id);
$view = new ViewModel(array(
'list' => $list,
));
return $view;
}