Zend\View\Renderer\PhpRenderer::render: Unable to render template - php

Unable to render file error in zf2.
I am working on a project for matrimonial site, in which I need to search data according to matched requirement but get an error.
Here is my code:
//SearchController.php in Project/src/Project/Controller
public function processAction()
{
if (!$this->request->isPost()) {
return $this->redirect()->toRoute(NULL ,
array( 'controller' => 'search',
'action' => 'index'
));
}
$post = $this->request->getPost();
$dbAdapter=$this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$form = new SearchForm($dbAdapter);
//$inputFilter = new RegisterFilter();
//$form->setInputFilter($inputFilter);
$form->setData($post);
if (!$form->isValid()) {
$model = new ViewModel(array(
'error' => true,
'form' => $form,
));
$model->setTemplate('project/search/index');
return $model;
}
$ageto = $this->getRequest()->getPost('ageto');
$agefrom = $this->getRequest()->getPost('agefrom');
$heightfrom = $this->getRequest()->getPost('heightfrom');
$heightto = $this->getRequest()->getPost('heightto');
$educationid = $this->getRequest()->getPost('educationid');
$cityid = $this->getRequest()->getPost('cityid');
$complexionid = $this->getRequest()->getPost('complexionid');
$religioncode = $this->getRequest()->getPost('religioncode');
$sql="SELECT * FROM projects WHERE YEAR(CURDATE())-YEAR(dob) BETWEEN ".$agefrom. " AND ".$ageto;
$sql.=" and heightcode BETWEEN ". $heightfrom." AND ". $heightto." and religioncode = ".$religioncode;
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$num=count($result);
if($num==0)
{
echo "No Matches Found";
}
else
{
$result = $statement->execute();
$selectData = array();
foreach ($result as $res) {
$selectData=$res;
}
return $selectData;
}
return $this->redirect()->toRoute(NULL , array(
'controller' => 'search',
'action' => 'confirm'
));
}
public function confirmAction()
{
$viewModel = new ViewModel();
return $viewModel;
}
index.phtml in Project/view/project/search
<html>
<head><link rel="stylesheet" href="/css/demo.css" type="text/css" ></head>
<section class="search">
<p> Welcome! </p>
<h2>Search Form</h2>
<?php if ($this->error): ?>
<p class="error">
There were one or more issues with your submission.
Please correct them as
indicated below.
</p>
<?php endif ?>
<?php
$form = $this->form;
$form->prepare();
$form->setAttribute('action', $this->url(NULL,array('controller'=>'Search', 'action' =>'process')));
$form->setAttribute('method', 'post');
$form->setAttribute('enctype','multipart/form-data');
echo $this->form()->openTag($form);
?>
<body>
<div align="left">
<table align="left" cellpadding="6">
<tr><th>Age:</th>
<td><?php
echo $this->formElement($form->get('agefrom'));
?>
<b>to </b>
<?php echo $this->formElement($form->get('ageto'));
?></td></tr>
<tr><th>Height:</th>
<td><?php
echo $this->formElement($form->get('heightfrom'));
?>
<b>to</b>
<?php echo $this->formElement($form->get('heightto'));
?></td></tr>
<tr><th>Education:</th>
<td><?php
echo $this->formElement($form->get('educationid'));
echo $this->formElementErrors($form->get('educationid'));?></td></tr>
<tr><th>City:</th>
<td><?php
echo $this->formElement($form->get('cityid'));
echo $this->formElementErrors($form->get('cityid'));?></td></tr>
<th>Complexion:</th>
<td><?php
echo $this->formElement($form->get('complexionid'));
echo $this->formElementErrors($form->get('complexionid'));?></td></tr>
<tr><th>Religion:</th>
<td><?php
echo $this->formElement($form->get('religioncode'));
echo $this->formElementErrors($form->get('religioncode'));?></td></tr>
<tr>
<td><?php
echo $this->formElement($form->get('submit'));
echo $this->formElementErrors($form->get('submit'));
?></td></tr>
<?php echo $this->form()->closeTag() ?>
</table>
</section>
</div>
But after clicking on submit I'm getting the renderer error:
Zend\View\Renderer\PhpRenderer::render: Unable to render template "project/search/process"; resolver could not resolve to a file
Module.config.php
<?php
return array(
'controllers' => array(
'invokables' => array(
'Project\Controller\Index' =>
'Project\Controller\IndexController',
'Project\Controller\Register' =>
'Project\Controller\RegisterController',
'Project\Controller\Login' =>
'Project\Controller\LoginController',
'Project\Controller\Search' =>
'Project\Controller\SearchController',
),
),
'router' => array(
'routes' => array(
'project' => array(
'type' => 'Literal',
'options' => array(
'route' => '/project',
'defaults' => array(
'__NAMESPACE__' => 'Project\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
// specific routes.
'default' => array(
'type' => 'Segment',
'options' => array(
'route' =>
'/[:controller[/:action]]',
'constraints' => array(
'controller' =>
'[a-zA-Z][a-zA-Z0-9_-]*',
'action' =>
'[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'project' => __DIR__ . '/../view',
),
'strategies' => array(
'ViewJsonStrategy',
),
),
);

Do you create file Project/view/project/search/process.phtml?

Related

Zend Form Duplicate Entry Email Exception

Having a registration zend form in view looks like this :
<?php
$form = $this->form;
if(isset($form)) $form->prepare();
$form->setAttribute('action', $this->url(NULL,
array('controller' => 'register', 'action' => 'process')));
echo $this->form()->openTag($form);
?>
<dl class="form-signin">
<dd><?php
echo $this->formElement($form->get('name_reg'));
echo $this->formElementErrors($form->get('name_reg'));
?></dd>
<dd><?php
echo $this->formElement($form->get('email_reg'));
echo $this->formElementErrors($form->get('email_reg'));
?></dd>
<dd><?php
echo $this->formElement($form->get('password_reg'));
echo $this->formElementErrors($form->get('password_reg'));
?></dd>
<dd><?php
echo $this->formElement($form->get('confirm_password_reg'));
echo $this->formElementErrors($form->get('confirm_password_reg'));
?></dd>
<br>
<dd><?php
echo $this->formElement($form->get('send_reg'));
echo $this->formElementErrors($form->get('send_reg'));
?></dd>
<?php echo $this->form()->closeTag() ?>
And RegisterController as following.
<?php
namespace Test\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;
use Test\Form\RegisterForm;
use Test\Form\RegisterFilter;
use Test\Form\LoginFormSm;
use Test\Form\LoginFilter;
use Test\Model\User;
use Test\Model\UserTable;
class RegisterController extends AbstractActionController
{
public function indexAction()
{
$this->layout('layout/register');
$form = new RegisterForm();
$form_sm = new LoginFormSm();
$viewModel = new ViewModel(array(
'form' => $form,
'form_sm' =>$form_sm,
));
return $viewModel;
}
public function processAction()
{
$this->layout('layout/register');
if (!$this->request->isPost()) {
return $this->redirect()->toRoute(NULL,
array( 'controller' => 'index'
)
);
}
$form = $this->getServiceLocator()->get('RegisterForm');
$form->setData($this->request->getPost());
if (!$form->isValid()) {
$model = new ViewModel(array(
'form' => $form,
));
$model->setTemplate('test/register/index');
return $model;
}
// Creating New User
$this->createUser($form->getData());
return $this->redirect()->toRoute(NULL, array (
'controller' => 'auth' ,
));
}
protected function createUser(array $data)
{
$userTable = $this->getServiceLocator()->get('UserTable');
$user = new User();
$user->exchangeArray($data);
$userTable->saveUser($user);
return true;
}
}
Also a RegisterForm where are declared all variables shown in index. Also RegisterFilter as following:
<?php
namespace Test\Form;
use Zend\InputFilter\InputFilter;
class RegisterFilter extends InputFilter
{
public function __construct()
{
$this->add(array(
'name' => 'email_reg',
'required' => true,
'filters' => array(
array(
'name' => 'StripTags',
),
array(
'name' => 'StringTrim',
),
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
'messages' => array(
\Zend\Validator\EmailAddress::INVALID_FORMAT => 'Email address format is invalid'
),
),
),
array(
'name' => 'AbstractDb',
'options' => array(
'domain' => true,
'messages' => array(
\Zend\Validator\Db\AbstractDb::ERROR_RECORD_FOUND => 'Current Email Already registered'
),
),
),
),
));
$this->add(array(
'name' => 'name_reg',
'required' => true,
'filters' => array(
array(
'name' => 'StripTags',
),
array(
'name' => 'StringTrim',
),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 140,
),
),
),
));
$this->add(array(
'name' => 'password_reg',
'required' => true,
'validators' => array(
array(
'name' => 'StringLength',
'options' =>array(
'encoding' => 'UTF-8',
'min' => 6,
'messages' => array(
\Zend\Validator\StringLength::TOO_SHORT => 'Password is too short; it must be at least %min% ' . 'characters'
),
),
),
array(
'name' => 'Regex',
'options' =>array(
'pattern' => '/[A-Z]\d|\d[A-Z]/',
'messages' => array(
\Zend\Validator\Regex::NOT_MATCH => 'Password must contain at least 1 digit and 1 upper-case letter'
),
),
),
),
));
$this->add(array(
'name' => 'confirm_password_reg',
'required' => true,
'validators' => array(
array(
'name' => 'Identical',
'options' => array(
'token' => 'password_reg', // name of first password field
'messages' => array(
\Zend\Validator\Identical::NOT_SAME => "Passwords Doesn't Match"
),
),
),
),
));
}
}
Problem
All i need is to throw a message when somebody tries to register and that e-mail is already registered. Tried with \Zend\Validator\Db\AbstractDb and added following validator to email in RegisterFilter as following
array(
'name' => 'AbstractDb',
'options' => array(
'domain' => true,
'messages' => array(
\Zend\Validator\Db\AbstractDb::ERROR_RECORD_FOUND => 'Current Email Already registered'
),
),
),
But that seems not to work.
Question: Is there a way to implement this validator in RegisterController?
Additional.
I've deleted from RegisterFilert validator and put inside Module.ph
'EmailValidation' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$validator = new RecordExists(
array(
'table' => 'user',
'field' => 'email',
'adapter' => $dbAdapter
)
);
return $validator;
},
And call it from RegisterController
$validator = $this->getServiceLocator()->get('EmailValidation');
if (!$validator->isValid($email)) {
// email address is invalid; print the reasons
$model = new ViewModel(array(
'error' => $validator->getMessages(),
'form' => $form,
));
$model->setTemplate('test/register/index');
return $model;
}
And when i use print_r inside view to check for it shows.
Array ( [noRecordFound] => No record matching the input was found ).
I want just to echo this 'No record matching the input was found'.
Fixed
Modified in RegisterController as following
$validator = $this->getServiceLocator()->get('EmailValidation');
$email_ch = $this->request->getPost('email_reg');
if (!$validator->isValid($email_ch)) {
// email address is invalid; print the reasons
$model = new ViewModel(array(
'error' => 'Following email is already registered please try another one',
'form' => $form,
));
$model->setTemplate('test/register/index');
return $model;
}
I had compared
if (!$validator->isValid($email_ch))
Before with nothing and that's why i needed to add first
$email_ch = $this->request->getPost('email_reg');
You don't have to do that in your controller, just try this in your RegisterFilter class :
First : Add $sm as parameter of the _construct() method :
public function __construct($sm) {....}
Second: Replace e-mail validation by this one :
$this->add ( array (
'name' => 'email_reg',
'required' => true,
'validators' => array(
array(
'name' => 'Zend\Validator\Db\NoRecordExists',
'options' => array(
'table' => 'user',
'field' => 'email',
'adapter' => $sm->get ( 'Zend\Db\Adapter\Adapter' ),
'messages' => array(
NoRecordExists::ERROR_RECORD_FOUND => 'e-mail address already exists'
),
),
),
),
)
);
When you call the RegisterFilter don't forget to pass the serviceLocator as parameter in your controller :
$form->setInputFilter(new RegisterFilter($this->getServiceLocator()));
Supposing you have this in your global.php File (config\autoload\global.php) :
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
To your previous request, ("I want just to echo this 'No record matching the input was found'")
$validator = $this->getServiceLocator()->get('EmailValidation');
$email_ch = $this->request->getPost('email_reg');
if (!$validator->isValid($email_ch)) {
// email address is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
$msg = $message;
}
$model = new ViewModel(array(
'error' => $msg,
'form' => $form,
));
$model->setTemplate('test/register/index');
return $model;
}

ERRORS Zend\InputFilter\Exception\RuntimeException

I am trying use zf2 to validate form, but have errors:
An error occurred
An error occurred during execution; please try again later.
Additional information:
Zend\InputFilter\Exception\RuntimeException
File:
C:\xampp\htdocs\ZEND\Users\Users\vendor\ZF2\library\Zend\InputFilter\Factory.php:395
Message:
Invalid validator specification provided; was neither a validator instance nor an array specification
Code:
<?php
namespace Users\Form;
use Zend\InputFilter\InputFilter;
class RegisterFilter extends InputFilter{
public function __construct(){
$this->add(array(
'name' => 'email',
'required' =>true,
'validators' => array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
),
),
));
$this->add(array(
'name' => 'user',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringLength'),
),
'validators' => array(
array(
'options' => array(
'encoding' => 'UTF-8',
'min' => 6,
'max' => 32,
),
),
),
));
}
}
RegisterForm
<?php
namespace Users\Form;
use Zend\Form\Form;
class RegisterForm extends Form {
public function __construct($name = null){
parent::__construct('Register');
$this->setAttribute('method', 'post');
$this->setAttribute('enctype', 'multipart/form-data');
$this->add(array(
'name' => 'user',
'attributes' => array(
'type' => 'text',
'required' => 'required'
),
'options' => array(
'label' => 'UserName',
),
));
$this->add(array(
'name' => 'pwd',
'attributes' => array(
'type' => 'password',
'required' => 'required'
),
'options' => array(
'label' => 'Password',
)
));
$this->add(array(
'name' => 'cpwd',
'attributes' => array(
'type' => 'password',
'required' => 'required'
),
'options' => array(
'label' => 'Comfirm Password',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Register',
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'email',
),
'options' => array(
'label' => 'Email',
),
'attributes' => array(
'required' => 'required',
),
'filters' => array(
array('name' => 'StringTrim')
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'messages' => array(
\Zend\Validator\EmailAddress::INVALID_FORMAT => 'Email Address Format is invalid'
)
)
)
)
));
}
}
RegisterController
<?php
namespace Users\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Users\Form\RegisterForm;
use Users\Form\RegisterFilter;
class RegisterController extends AbstractActionController{
public function indexAction(){
$form = new RegisterForm();
$viewmodel = new ViewModel(array('form' => $form));
return $viewmodel;
}
public function processAction(){
if(!$this->request->isPost()){
return $this->redirect()-> toRoute(NULL,
array( 'controller' => 'register',
'action' => 'index',
));
}
$post = $this->request->getPost();
$form = new RegisterForm();
$inputFilter = new RegisterFilter();
$form->setInputFilter($inputFilter);
$form->setData($post);
if(!$form->isValid()){
$model = new ViewModel(array(
'error' => true,
'form' => $form,
));
$model ->setTemplate('users/register/index');
return $model;
}
return $this->redirect()->toRoute(NULL,array(
'controller' => 'register',
'action' => 'confirm',
));
}
public function confirmAction(){
$viewmodel = new ViewModel();
return $viewmodel;
}
}
index.phtml
<section class = 'register'>
<h2> Register </h2>
<?php if($this -> error): ?>
<p class='error'> have errors </p>
<?php endif ?>
<?php
$form = $this->form;
$form -> prepare();
$form -> setAttribute('action', $this->url(NULL,
array('controller' => 'Register', 'action' => 'process')));
$form -> setAttribute('method','post');
echo $this->form()->openTag($form);
?>
<dl class='zend_form'>
<dt><?php echo $this->formLabel($form -> get('user')) ;?> </dt>
<dd> <?php echo $this->formElement($form->get('user')) ;?>
<?php echo $this->formElementErrors($form->get('user')) ;?>
</dd>
<dt><?php echo $this->formLabel($form -> get('email'));?></dt>
<dd><?php echo $this->formElement($form-> get('email')) ;?>
<?php echo $this->formElementErrors($form -> get('email')) ;?>
</dd>
<dt><?php echo $this->formLabel($form -> get('pwd')) ;?></dt>
<dd><?php echo $this->formElement($form->get('pwd')) ;?>
<?php echo $this->formElementErrors($form->get('pwd')) ;?>
</dd>
<dt><?php echo $this->formLabel($form ->get('cpwd'));?></dt>
<dd><?php echo $this->formElement($form->get('cpwd'));?>
<?php echo $this->formElementErrors($form->get('cpwd'))?>
</dd>
<dd><?php echo $this->formElement($form->get('submit'));?>
<?php echo $this->formElementErrors($form->get('submit'));?>
</dd>
</dl>
<?php echo $this->form()->closeTag()?>
</section>
Your validator structure is wrong.
The validators key is expecting an array of validators. You are supplying the validator name and options directly.
Change this:
this->add(array(
'name' => 'email',
'required' =>true,
'validators' => array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
),
),
));
To:
this->add(array(
'name' => 'email',
'required' =>true,
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
),
)
//Another validator here ..
),
));

cakephp fetch in default layout not working

Hello i'm trying to fetch an element in my default layout but it's not displaying anything ive followed cakephp documentation about displaying blocks and i havent found my error.
My MenusController.php
<?php
class MenusController extends AppController{
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow();
}
public function get_menu(){
if ($this->Auth->user()['role'] == 'admin'){
$this->set('dashboard_menu',$this->dashboard_menu_admin());
}
else
$this->set('dashboard_menu',$this->dashboard_menu_user());
}
private function dashboard_menu_admin(){
$dashBoardMenu = array(
array(
'elementName' => 'Usuarios',
'iconName'=> 'user',
'action' => 'users'
),
array('elementName' => 'Personal',
'iconName' => 'user',
'action'=>'personal'
),
array('elementName' => 'Resumen Semanal',
'iconName' => 'edit',
'action' => 'resumen'
),
array('elementName' => 'Estadisticas',
'iconName' => 'signal',
'action' => '#'
),
array('elementName' => 'Tareas',
'iconName' => 'check',
'action' => '#'
),
array('elementName' => 'Calendario',
'iconName' => 'calendar',
'action' => '#'),
array('elementName' => 'Nube',
'iconName' => 'cloud',
'action'=> '#')
);
return $dashBoardMenu;
}
private function dashboard_menu_user(){
$dashBoardMenu = array(
array(
'elementName' => 'Usuarios',
'iconName'=> 'user',
'action' => 'users'
),
array('elementName' => 'Resumen Semanal',
'iconName' => 'edit',
'action' => 'resumen'
),
array('elementName' => 'Estadisticas',
'iconName' => 'signal',
'action' => '#'
),
array('elementName' => 'Tareas',
'iconName' => 'check',
'action' => '#'
),
array('elementName' => 'Calendario',
'iconName' => 'calendar',
'action' => '#'),
array('elementName' => 'Nube',
'iconName' => 'cloud',
'action'=> '#')
);
return $dashBoardMenu;
}
}
In View/Menus/get_menu.ctp
<?php
$this->start('menu');
echo $this->element('menu/dashboard_menu',array('menuItems' => $dashboard_menu));
$this->end();
?>
PART OF view/layouts/default.ctp
<div class="container-fluid" id="container">
<div class="row-fluid">
<?php if ($logged_in): ?>
<?php echo $this->fetch('menu'); //THiS IS NOT DISPLAYING ANYTHING ?>
<?php endif; ?>
<div class="span9" id="content">
<?php echo $this->Session->flash(); ?>
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->fetch('content'); ?>
</div>
</div>
</div>
I'm trying to print an echo "something" betwee start and end methods and ive got nothing.
i think its not fetching but i dont know why
Somebody can help me. thanks.

Zend Framework 2: Invisible Captcha

I have a little problem generate captcha in ZF2
Here is my Controller:
public function indexAction()
{
$form = new RegisterForm();
return array('form' => $form);
}
RegisterForm class:
public function __construct($name = null)
{
$this->url = $name;
parent::__construct('register');
$this->setAttributes(array(
'method' => 'post'
));
$this->add(array(
'name' => 'password',
'attributes' => array(
'type' => 'password',
'id' => 'password'
)
));
$this->get('password')->setLabel('Password: ');
$captcha = new Captcha\Image();
$captcha->setFont('./data/captcha/font/arial.ttf');
$captcha->setImgDir('./data/captcha');
$captcha->setImgUrl('./data/captcha');
$this->add(array(
'type' => 'Zend\Form\Element\Captcha',
'name' => 'captcha',
'options' => array(
'label' => 'Captcha',
'captcha' => $captcha,
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'button',
'value' => 'Register',
),
));
}
View: index.phtml:
...
<div class="group">
<?php echo $this->formlabel($form->get('captcha')); ?>
<div class="control-group">
<?php echo $this->formElementErrors($form->get('captcha')) ?>
<?php echo $this->formCaptcha($form->get('captcha')); ?>
</div>
</div>
...
Above code generate png images in data/captcha folder, but i can't generate them in view.
FireBug shows img element and url, but url to image seems to be empty.
Thanks for any help.
You have to set the img url correctly and define the route in your module.config.php
Controller
public function indexAction()
{
$form = new RegisterForm($this->getRequest()->getBaseUrl().'test/captcha');
return array('form' => $form);
}
remember to change the test/captcha to your own base url
in your registerForm class
public function __construct($name)
{
//everything remain the same, just change the below statement
$captcha->setImgUrl($name);
}
add this to your module.config.php, as your main route child
'may_terminate' => true,
'child_routes' => array(
'registerCaptcha' => array(
'type' => 'segment',
'options' => array(
'route' => '/[:action[/]]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'action' => 'register',
),
),
),
'captchaImage' => array(
'type' => 'segment',
'options' => array(
'route' => '/captcha/[:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'controller',
'action' => 'generate',
),
),
),
),
remember to change the controller under captcha image, the action generate is actually generating the captcha image file
add this to your controller file as well
public function generateAction()
{
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('Content-Type', "image/png");
$id = $this->params('id', false);
if ($id) {
$image = './data/captcha/' . $id;
if (file_exists($image) !== false) {
$imagegetcontent = #file_get_contents($image);
$response->setStatusCode(200);
$response->setContent($imagegetcontent);
if (file_exists($image) == true) {
unlink($image);
}
}
}
return $response;
}
with these, it should be working fine

How to use $_GET with paginator?

I added in my project sorting data by select->order by $GET-variables. But when I navigate through the pages by paginator, of course this variables are not passing on the next page. What is the best way to pass this variables and use it with paginator?
Controller:
public function indexAction()
{
$sortForm = new \Records\Form\SortingForm();
$field = 'date';
$order = 'desc';
$request = $this->getRequest();
if ($request->isGet()){
$sortForm->setValidationGroup(array('field', 'order'));
$sortData = $request->getQuery()->toArray();
$sortForm->setData($sortData);
if($sortForm->isValid()) {
$sortForm->getData($sortData);
$field = (string) $this->params()->fromQuery('field', 'date');
$order = (string) $this->params()->fromQuery('order', 'desc');
}
}
$query = $this->getRecordsTable()->fetchAll($field, $order);
$paginator = new Paginator\Paginator(new Paginator\Adapter\Iterator($query));
$paginator->setCurrentPageNumber($this->params()->fromRoute('page', 1));
$paginator->setItemCountPerPage(25);
$vm = new ViewModel(array('records' => $paginator));
Model:
public function fetchAll($field, $order)
{
$this->field = $field;
$this->order = $order;
$resultSet = $this->tableGateway->select(function (Select $select) {
$select->columns(array('date', 'name', 'email', 'homepage', 'text', 'image', 'file'));
$select->order($this->field.' '.$this->order);
});
$resultSet->buffer();
$resultSet->next();
return $resultSet;
}
Form:
public function __construct($name = null)
{
parent::__construct('records');
$this->setAttribute('method', 'get');
$this->add(array(
'name' => 'field',
'required' => false,
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Sort by: ',
'value_options' => array(
'date' => 'Date',
'email' => 'E-mail',
'name' => 'Username',
),
)));
$this->add(array(
'name' => 'order',
'required' => false,
'type' => 'Zend\Form\Element\Select',
'options' => array(
'value_options' => array(
'asc' => 'ascending',
'desc' => 'descending',
),
)));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
Paginator view:
<!-- Numbered page links -->
<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
<a href="<?php echo $this->url($this->route, array('page' => $page)); ?>">
<?php echo $page; ?>
</a> |
<?php else: ?>
<?php echo $page; ?> |
<?php endif; ?>
<?php endforeach; ?>
And another one: when I passing get-variables, the query string looks like http://guest-book.me/page/7?field=date&order=asc&submit=Go How I can do not send pair submit=>value?
Thank you for help! :)
Firstly, you need to make sure the route you're using for the Paginator has a Query String child route, I would recommend having a route specifically for use with listings with pagination, an example:
'router' => array(
'routes' => array(
'paginator_route' => array(
'type' => 'segment',
'options' => array(
'route' => '/list/:controller/:action[/page/:page][/]',
'constraints' => array(
//'__NAMESPACE__' => 'Application\Controller',
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'page' => '[0-9]+',
),
'defaults' => array(
'controller' => 'index',
'action' => 'list',
'page' => 1,
),
),
'may_terminate' => true, // with or without Query string
'child_routes' => array(
'query' => array( // allows us to match query string
'type' => 'Query',
'options' => array(
'defaults' => array(
// Query string defaults here..
)
)
),
),
),
You now need to modify your pagination view to allow us to use current parameters as a base when generating the new links:
<!-- Numbered page links -->
<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
<?php // the last param allows us to reuse the matched params ?>
<a href="<?php echo $this->url($this->route, array('page' => $page), TRUE); ?>">
<?php echo $page; ?>
</a> |
<?php else: ?>
<?php echo $page; ?> |
<?php endif; ?>
<?php endforeach; ?>
Your pagination links should now retain the Query string values :-)
you can create a helper that pass a GET parameter to url too. i've created a sample module for this : https://github.com/samsonasik/SanSamplePagination

Categories