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
Related
HI i Want to create Alpha Pager search , search is working fine but when i click search it disturb UI like load header and menu second time and site start showing menu again
Here is admin.php view page:
<?php
/* #var $this AreaController */
/* #var $model Area */
$this->breadcrumbs = array(
'Areas' => array('index'),
'Manage',
);
?>
<h1>Manage Areas</h1>
<div>
<?php
echo CHtml::ajaxLink('F', Yii::app()->createUrl('area/admin'), array('data' => array('q' => 'F'), 'update' => '#area-grid'), array());
echo CHtml::ajaxLink('E', Yii::app()->createUrl('area/admin'), array('data' => array('q' => 'E'), 'update' => '#area-grid'), array());
//echo CHtml::link('S', array('area/admin', 'q' => 'S'), array('target' => '_blank'));
?>
</div>
<?php
$this->widget('bootstrap.widgets.TbGridView', array(
'id' => 'area-grid',
'itemsCssClass' => 'table-bordered items',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
array(
'class' => 'editable.EditableColumn',
'name' => 'Area',
'headerHtmlOptions' => array('style' => 'width: 110px'),
'editable' => array(//esditable section
'url' => $this->createUrl('area/updateEditable', array('model' => 'Area', 'field' => 'status')),
'placement' => 'right',
)
),
array(
'class' => 'editable.EditableColumn',
'name' => 'status',
'headerHtmlOptions' => array('style' => 'width: 100px'),
'editable' => array(
'type' => 'select',
//'url' => Area::getStatusList(),
'url' => $this->createUrl('area/updateEditable', array('model' => 'Area', 'field' => 'status')),
'source' => $this->createUrl('area/getStatuses'),
'options' => array(//custom display
'display' => 'js: function(value, sourceData) {
var selected = $.grep(sourceData, function(o){ return value == o.value; }),
colors = {"Active": "green", "InActive": "red"};
$(this).text(selected[0].text).css("color", colors[value]);
}'
),
//onsave event handler
'onSave' => 'js: function(e, params) {
console && console.log("saved value: "+params.newValue);
}',
'htmlOptions' => array(
'data-username' => '$data->status'
)
)
),
),
));
?>
Controller admin action code:
public function actionAdmin() {
$model = new Area('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['Area']))
$model->attributes = $_GET['Area'];
$this->render('admin', array(
'model' => $model,
));
}
Model search function code:
public function search() {
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$criteria = new CDbCriteria;
if (isset($_GET['q'])) {
$criteria->condition = 'Area like "' . $_GET["q"] . '%" ';
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
$criteria->compare('id', $this->id);
$criteria->compare('Area', $this->Area, true);
$criteria->compare('status', $this->status, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
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;
}
I cant list data in grid using yii framework.My controller is Sitecontroller.php,My view is list_jobseeker.php .I got the error "Fatal error: Call to a member function getData() on a non-object ".Anybody help me?
My controller code
public function actionlist_jobseeker()
{
$session_id=Yii::app()->session['user_id'];
if ($session_id == "")
{
$this->redirect( array('/employee/site/login'));
}
$user_id =$session_id;
$models = Yii::app()->db->createCommand()
->select('*')
->from('job_seeker_profile s')
->join('job_profile j','s.user_id = j.user_id')
->order('s.id')
->queryAll();
$this->render('list_jobseeker',array('models' =>$models));
}
View- list_jobseeker.php
<h1>View Jobseeker</h1>
<div class="flash-success">
</div>
<div class="form">
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'rates-phase-grid',
'htmlOptions' => array('class' => 'table table-striped table-bordered table-hover'),
'dataProvider'=>new CArrayDataProvider($models),
'columns' => array(
array(
'name' => 'Name',
'type' => 'raw',
'value' => 'CHtml::encode($data[*]->name)',
'htmlOptions' => array('style'=>'width:90px;','class'=>'zzz'),
),
array(
'name' => 'Email',
'type' => 'raw',
'value' => 'CHtml::encode($data[*]->email)',
'htmlOptions' => array('style'=>'width:250px;','class'=>'zzz')
),
array(
'name' => 'Password',
'type' => 'raw',
'value' => 'CHtml::encode($data[*]->password)',
'htmlOptions' => array('style'=>'width:90px;','class'=>'zzz')
),
array(
'name' => 'Contact No',
'type' => 'raw',
'value' => 'CHtml::encode($data[*]->contact_no)',
'htmlOptions' => array('style'=>'width:40px;','class'=>'zzz')
),
array(
'name' => 'Gender',
'type' => 'raw',
'value' => 'CHtml::encode($data[*]->gender)',
'htmlOptions' => array('style'=>'width:40px;','class'=>'zzz')
),
array(
'class' =>'CButtonColumn',
'deleteConfirmation'=>'Are you sure you want to delte this item?',
'template'=>'{update}{delete}',
'buttons' =>array('update'=>array(
'label'=>'edit',
'url'=>'Yii::app()->controller->createUrl("UpdateJob",array("id"=>$data["id"]))',
),
'delete'=>array('label'=>'delete',
'url'=>'Yii::app()->controller->createUrl("DeleteJob",array("id"=>$data["id"]))'),
)
)
),
));
?>
dataProvider should be a CDataProvider instance. You are passing in an array: $model. You could wrap this in a CArrayDataProvider:
'dataProvider' => new CArrayDataProvider($model),
A couple of other issues:
a) Your gridview expects $data to be an object and not an array. Either alter all $data->* instances to $data[*] or use CActiveDataProvider and the CActiveRecord instance for the job_seeker_profile table
b) By convention $model usually refers to a single CModel instance. Your array should therefore be named something else in plural e.g $items
I use this:
$data = ...::model()->findAll();
$dataProvider=new CArrayDataProvider('Class of your object');
$dataProvider->setData($data);
$dataProvider->keyField = "primary key of your model";
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
...
array( 'class'=>'CButtonColumn',
'template' => '{ver}',
'buttons' => array(
'ver' => array(
'url'=>'"?id=".$data["..."]',
'imageUrl'=> Yii::app()->baseUrl.'/images/view.png', //Image URL of the button.
),
)
),
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 ..
),
));
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