I am new to Zf2. I have user and admin module. When user is logged in I made profile in admin where he change his profile and also password.
Now I am working in change password, but I cannot understand, how to code for change password. My code is given below:
My ProfileController is:
<?php
namespace Admin\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Admin\Model\Profile;
use Admin\Form\ProfileForm;
class ProfileController extends AbstractActionController
{
protected $profileTable;
public function getAuthService()
{
$this->authservice = $this->getServiceLocator()->get('AuthService');
return $this->authservice;
}
public function indexAction()
{
$this->layout("layout/layout_admin");
/* this is used to show user email of logined user. */
$user_email = $this->getAuthService()->getStorage()->read();
// below condition is new and for back browser validation
if (!$this->getServiceLocator()
->get('AuthService')->hasIdentity()) {
return $this->plugin(redirect)->toRoute('login', array('action' => 'index'));
}
return new ViewModel(array(
'admin_profile' => $this->getProfileTable()->fetchAll($user_email),
));
}
public function editAction()
{
$this->layout("layout/layout_admin");
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('login', array(
'action' => 'index'
));
}
// Get the Profile with the specified id. An exception is thrown
// if it cannot be found, in which case go to the index page.
try {
$profile = $this->getProfileTable()->getProfile($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('profile', array(
'action' => 'index'
));
}
$form = new ProfileForm();
$form->bind($profile);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($profile->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getProfileTable()->saveProfile($profile);
// Redirect to profile
return $this->redirect()->toRoute('profile');
}
}
return array(
'id' => $id,
'form' => $form,
);
}
public function changepasswordAction()
{
$this->layout("layout/layout_admin");
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('login', array(
'action' => 'index'
));
}
// Get the Profile with the specified id. An exception is thrown
// if it cannot be found, in which case go to the index page.
try {
$profile = $this->getProfileTable()->getProfile($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('profile', array(
'action' => 'index'
));
}
$form = new ProfileForm();
$form->bind($profile);
$form->get('submit')->setAttribute('value', 'Change');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($profile->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
echo "form is valid now save the data";
}else echo "form is invalid, don't save data";
}
return array(
'id' => $id,
'form' => $form,
);
}
public function getProfileTable()
{
if (!$this->profileTable) {
$sm = $this->getServiceLocator();
$this->profileTable = $sm->get('Admin\Model\ProfileTable');
}
return $this->profileTable;
}
}
ProfileForm.php:
<?php
namespace Admin\Form;
use Zend\Form\Form;
class ProfileForm extends Form
{
public function __construct($name = null)
{
parent::__construct('profile');
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'name',
'attributes' => array(
'type' => 'text',
'required' => 'required',
),
'options' => array(
'label' => 'Name',
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'text',
'required' => 'required',
),
'options' => array(
'label' => 'Email',
),
));
$this->add(array(
'name' => 'old_password',
'attributes' => array(
'type' => 'password',
'required' => 'required',
),
'options' => array(
'label' => 'Old Password ',
),
));
$this->add(array(
'name' => 'new_password',
'attributes' => array(
'type' => 'password',
'required' => 'required',
),
'options' => array(
'label' => 'New Password ',
),
));
$this->add(array(
'name' => 'confirm_password',
'attributes' => array(
'type' => 'password',
'required' => 'required',
),
'options' => array(
'label' => 'Confirm Password ',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}
Model/Profile.php:
<?php
namespace Admin\Model;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class Profile implements InputFilterAwareInterface
{
public $id;
public $name;
public $email;
public $password;
protected $inputFilter;
public function exchangeArray($data)
{
$this->id = (!empty($data['id'])) ? $data['id'] : null;
$this->name = (!empty($data['name'])) ? $data['name'] : null;
$this->email = (!empty($data['email'])) ? $data['email'] : null;
$this->password = (!empty($data['password'])) ? $data['password'] : null;
}
public function __set($name, $value) {
$method = 'set' . $name;
if (!method_exists($this, $method)) {
throw new Exception('Invalid Method');
}
$this->$method($value);
}
public function __get($name) {
$method = 'get' . $name;
if (!method_exists($this, $method)) {
throw new Exception('Invalid Method');
}
return $this->$method();
}
public function getArrayCopy()
{
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'name',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
));
$inputFilter->add(array(
'name' => 'email',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
Model/ProfileTable.php:
<?php
namespace Admin\Model;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Adapter\Adapter;
class ProfileTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll($user_email)
{
$resultSet = $this->tableGateway->select(array('email' =>$user_email));
return $resultSet;
}
public function getProfile($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current('id');
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function saveProfile(Profile $profile)
{
$data = array(
'name' => $profile->name,
'email' => $profile->email,
);
$id = (int) $profile->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getProfile($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Profile id does not exist');
}
}
}
}
view/changepassword.phtml:
<div class="jumbotron">
<?php
$title = 'Change your password Here:';
$this->headTitle($title);
?>
<h2 align="center"><?php echo $this->escapeHtml($title); ?></h2>
<div align="right">
View Profile
</div>
<br/>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('profile',
array(
'action' => 'changepassword',
'id' => $this->id,
)
));
$form->prepare();
?>
<div align="center">
<?php
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('old_password'));
echo "<br/>";
echo $this->formRow($form->get('new_password'));
echo "<br/>";
echo $this->formRow($form->get('confirm_password'));
echo "<br/>";
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
?>
Cancel
</div>
</div>
I complete this with myself. Answer and best solution for change password is as follow:
changepassword.phtml:
<div class="jumbotron">
<h2 align="center">Change Your Password Here:</h2>
<div align="right">
View Profile
</div>
<br/>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('profile',
array(
'action' => 'changepassword',
'id' => $this->id,
)
));
$form->prepare();
?>
<?php echo $error; ?>
<div align="center">
<?php
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('old_password'));
echo "<br/>";
echo $this->formRow($form->get('new_password'));
echo "<br/>";
echo $this->formRow($form->get('confirm_password'));
echo "<br/>";
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
?>
Cancel
</div>
</div>
Add this code in Profile.php
public function getInputFilter2()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'old_password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 100,
),
),
),
));
$inputFilter->add(array(
'name' => 'new_password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 100,
),
),
),
));
$inputFilter->add(array(
'name' => 'confirm_password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 100,
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
Add below function in ProfileTable.php
public function updatePassword($password,Profile $profile)
{
$data = array(
'password' => md5($password),
);
$id = (int) $profile->id;
if ($this->getProfile($id))
{
$this->tableGateway->update($data, array('id' => $id));
}
else
{
throw new \Exception('Profile id does not exist');
}
}
Add the following code in ProfileController.php
public function changepasswordAction()
{
$this->layout("layout/layout_admin");
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('login', array(
'action' => 'index'
));
}
// below condition is new and for back browser validation
if (!$this->getServiceLocator()
->get('AuthService')->hasIdentity()) {
return $this->plugin(redirect)->toRoute('login', array('action' => 'index'));
}
$error = "";
$password="";
// Get the Profile with the specified id. An exception is thrown
// if it cannot be found, in which case go to the index page.
try {
$profile = $this->getProfileTable()->getProfile($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('profile', array(
'action' => 'index'
));
}
$form = new ProfileForm();
$form->bind($profile);
$form->get('submit')->setAttribute('value', 'Change');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($profile->getInputFilter2());
$form->setData($request->getPost());
if(($profile->password == md5($this->params()->fromPost('old_password')))AND($form->isValid()))
{
if($this->params()->fromPost('new_password') == $this->params()->fromPost('confirm_password'))
{
$password=$this->params()->fromPost('confirm_password');
$this->getProfileTable()->updatePassword($password,$profile);
//Redirect to profile
return $this->redirect()->toRoute('profile');
}
else
{
$error="<b>Error: </b>New Password and Confirm password didn't match";
}
}
else
{
$error="<b>Error: </b>Old Password didn't match";
}
}
return array(
'id' => $id,
'form' => $form,
'error' => $error,
);
}
Related
I am creating page to insert data like a book. Where I'm using zend form fieldset and collection. Fieldset have only two fields heading field and content field. Heading and sub-heading have same content(fields).
Ex:
1: Heading Content
1.1: Sub Heading
Content
1.1.1: Sub Heading
Content
1.1.2: Sub Heading
Content
1.1.2.1: Sub Heading
Content
1.1.2.2: Sub Heading
Content
...
1.1.3: Sub Heading
Content
..
1.2: Sub Heading
Content
...
2: Heading Content
Note: here indexing is just to show the parent child relationship.
Code are below:
This is main form.
class BookPointlForm extends Form
{
public function __construct($name = null)
{
parent::__construct('Form');
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'points',
'attributes' => array(
'class'=> 'point_collection '
),
'options' => array(
'label' => 'Add Book Points',
'count' => 1,
'should_create_template' => true,
'allow_add' => true,
'target_element' => array(
'type' => 'Book\Form\BookPointMainFieldset',
),
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Submit',
'id' => 'submitbutton',
'class' => 'btn btn-primary pull-right',
),
));
}
}
This fieldset is called in BookPointlForm's points collection
class BookPointMainFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('Fieldset');
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'points',
'attributes' => array(
'class'=> 'point_collection '
),
'options' => array(
'label' => 'Add Book Points',
'count' => 1,
'should_create_template' => true,
'allow_add' => true,
'target_element' => array(
'type' => 'Book\Form\BookPointFieldset',
),
),
));
$this->add(array(
'name' => 'add_nested_point',
'type' => 'Button',
'attributes' => array(
'value' => 'Add nested point',
'class'=> 'add_nested_point'
),
'options' => array(
'label' => 'Add Nested Point',
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'nested-points',
'attributes' => array(
'class'=> 'nested_point_collection '
),
'options' => array(
'label' => 'Add Book Points',
'count' => 1,
'should_create_template' => true,
'allow_add' => true,
'target_element' => array(
'type' => 'Book\Form\BookPointFieldset',
),
),
));
}
public function exchangeArray($data) {
}
public function getInputFilterSpecification()
{
return array(
'weight' => array(
'required' => true,
),
);
}
}
This is main fieldset it contents heading and heading's content
class BookHeadingFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct($name = null)
{
$kraHeadingText = '';
// we want to ignore the name passed
parent::__construct('BookHeadingFieldset');
// $this
// ->setHydrator(new ClassMethodsHydrator(false))
// ->setObject(new KraHeading())
;
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
'attributes' => array(
'value' => ''
)
));
$this->add(array(
'name' => 'manualHeadingText',
'type' => 'Textarea',
'options' => array(
'label' => 'Heading',
'label_options' => [
'disable_html_escape' => true
],
),
'labelOptions' => array(
'disable_html_escape' => true,
),
'attributes' => array(
'class' => 'form-control',
'placeholder'=>"Enter heading",
'COLS'=>"150",
// 'required' => 'true',
),
));
}
public function exchangeArray($data) {
}
public function getInputFilterSpecification()
{
return array();
}
}
...
If I fill in only password or only password-retype then it passes the validation.
If I fill in password and password-retype and they differ then it does not pass the validation.
What do i do wrong?!
$inputFilter->add(array(
'name' => 'password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 6,
'max' => 128,
),
),
),
));
$inputFilter->add(array(
'name' => 'retype-password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 6,
'max' => 128
),
),
array(
'name' => 'Identical',
'options' => array(
'token' => 'password'
)
)),
));
Form:
$form = $this->form;
$form->setAttribute('action', $this->url(
'users_update',
array(
'action' => 'edit',
'id' => $this->id,
)
));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('username'));
echo $this->formRow($form->get('email'));
echo $this->formRow($form->get('password'));
echo $this->formRow($form->get('retype-password'));
echo '<br />';
echo $this->formSubmit($form->get('submit'));
echo '<br />';echo '<br />';
echo $this->form()->closeTag();
update method:
public function updateAction() {
$form = new UsersForm();
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('admin');
}
$user = $this->getUsersTable()->getUser( $id );
$request = $this->getRequest();
if ( $request->isPost()) {
if( $request->getPost('password') == '' || $request->getPost('retype-password') == '' ){
$request->getPost()->set('password' , $user->password);
$request->getPost()->set('retype-password' , $user->password);
}
$users = new Users();
$form->setInputFilter($users->getInputFilter());
$form->setData($request->getPost());
$form->isValid();
if ($form->isValid()) {
$users->exchangeArray($form->getData());
$this->getUsersTable()->saveUser($users , $id);
return $this->redirect()->toRoute('users_list');
}
}
$form->bind($user);
$form->get('submit')->setValue('update');
return array(
'id' => $id,
'form' => $form
);
}
So there you have it. This piece
if ($request->getPost('password') == '' || $request->getPost('retype-password') == '' )
{
$request->getPost()->set('password' , $user->password);
$request->getPost()->set('retype-password' , $user->password);
}
causes the symptom. You should have && instead of ||.
I have a form which has 'rows' added dynamically using Zend\Form\Element\Collection. This works fine, but I am struggling to add the validation for these rows.
So far my code looks something like the following. I presume I need to pass something to InputFilter\InputFilter::add() but I can't figure out what:
<?php
class EditForm extends \Zend\Form\Form
{
public function __construct()
{
parent::__construct('edit');
$this->setUpFormElements();
$this->setupInputFilters();
}
protected function setUpFormElements()
{
$fieldset = new \Zend\Form\Fieldset;
$nameElement = new \Zend\Form\Element\Text('name');
$fieldset->add($nameElement);
$descriptionElement = new \Zend\Form\Element\Text('description');
$fieldset->add($description);
$this->add(
array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'rows',
'options' => array(
'label' => 'Edit Rows',
'should_create_template' => true,
'allow_add' => true,
'target_element' => $fieldset,
)
)
);
return $this;
}
public function setupInputFilters()
{
$filter = new \Zend\InputFilter\InputFilter();
$filter->add(
array(
'name' => 'rows',
'required' => true,
'validators' => array(
// Not sure what to do here!
)
)
);
return $this;
}
}
I think you need to add the input filter to the getInputFilterSpecification method of the fieldset you are adding dynamically
class Row extends Fieldset implements InputFilterProviderInterface
{
$this->add(array(
'name' => 'yourFieldset',
'options' => array(
'label' => 'One of your fieldset elements'
),
'attributes' => array(
'required' => 'required'
)
));
$this->add(array(
'name' => 'fields',
'options' => array(
'label' => 'Another fieldset element'
),
'attributes' => array(
'required' => 'required'
)
));
public function getInputFilterSpecification()
{
return array(
'yourFieldset' => array(
'required' => true,
),
'fields' => array(
'required' => true,
'validators' => array(
array(
'name' => 'Float'
)
)
)
);
}
then in your form you need to set the validation group
class EditForm extends Form
{
public function __construct()
{
$this->add(
array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'rows',
'options' => array(
'label' => 'Edit Rows',
'should_create_template' => true,
'allow_add' => true,
'target_element' => $fieldset,
)
)
);
$this->setValidationGroup(array(
'csrf',
'row' => array(
'yourFieldset',
'fields',
)
));
}
}
Hello to all zend coders. I am newbie to zend, doing code for manage pages through DB.
I want to use URL for these pages like this:
www.domainname.com/about-us
www.domainname.com/contact-us
...
Table name is 'cms_page' & attributes are:
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`page_key` varchar(255) NOT NULL,
`content` longtext NOT NULL,
`added_on` datetime NOT NULL,
I have done R&D for this and here are code:
// in module.config.php
'navigation' => array(
'default' => array(
'account' => array(
'label' => 'Account',
'route' => 'node',
'params' => array(
'id' => '2',
),
'pages' => array(
'home' => array(
'label' => 'Dashboard',
'route' => 'node',
'params' => array(
'id' => '1',
'link' => '/test'
),
),
'login' => array(
'label' => 'Sign In',
'route' => 'node',
'params' => array(
'id' => '5',
'link' => '/about-us'
),
),
'logout' => array(
'label' => 'Sign Out',
'route' => 'node',
'params' => array(
'id' => '3',
),
),
),
),
),
),
'router' => array(
'routes' => array(
'home' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'index',
),
),
),
'node' => array(
'type' => 'Application\Router\Alias',
'options' => array(
'route' => '/node[/:id]',
'constraints' => array(
'id' => '[0-9]+'
),
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Index',
'action' => 'index',
'id' => '0'
),
),
'may_terminate' => true,
),
),
),
// In Module.php
public function onBootstrap(MvcEvent $e)
{
$app = $e->getApplication();
$sm = $app->getServiceManager();
$sm->get('translator');
$sm->get('viewhelpermanager')->setFactory('controllerName', function($sm) use ($e) {
$viewHelper = new View\Helper\ControllerName($e->getRouteMatch());
return $viewHelper;
});
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$sm->setFactory('Navigation', 'Zend\Navigation\Service\DefaultNavigationFactory', true);
$alias = $sm->get('Application\Router\Alias');
$nav = $sm->get('Navigation');
$alias->setNavigation($nav);
}
public function getServiceConfig()
{
return array(
'factories' => array(
'Application\Router\Alias' => function($sm) {
$alias = new \Application\Router\Alias('/node[/:id]');
return $alias;
},
)
);
}
// Application\src\Application\Router
namespace Application\Router;
use Traversable;
use Zend\Mvc\Router\Exception;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\RequestInterface as Request;
use Zend\Mvc\Router\Http;
use Zend\Mvc\Router\Http\Segment as Segment;
class Alias extends Segment
{
private static $_navigation = null;
public function match(Request $request, $pathOffset = null)
{
$uri = $request->getUri();
$path = $uri->getPath();
$items = self::$_navigation->findAllBy('route', 'node');
$params = null;
if($items != null){
$t = sizeof($items);
for ($i=0; $i getParams();
if (isset($params['link']) && $params['link']==$path){
echo $uri->setPath('/'.$item->getRoute().'/'.$params['id']);
$request->setUri($uri);
break;
}
}
}
return parent::match($request, $pathOffset);
}
public function setNavigation($navigation){
self::$_navigation = $navigation;
}
protected function buildPath(array $parts, array $mergedParams, $isOptional, $hasChild, array $options)
{
if(isset($mergedParams['link'])){
return $mergedParams['link'];
}
return parent::buildPath($parts, $mergedParams, $isOptional, $hasChild, $options = array());
}
}
When I run this url www.domainname.com/about-us on browser getting 404 error.
Please help me where am I wrong and what code need to add or edit?
You can use the a Zend_Controller_Router_Route as an alternative. Here is a quick tutorial on how to do so:
http://www.codexperience.co.za/post/hiding-url-parameters-names-using-zend-routers
I am trying to create a custom element where I can pre-set an entity namespace say -- Application\Entity\User and easily add that element to any form. I have an issue with injecting the doctrine em in form elements -- I found this post about the form_elements key in configuration but it doesnt work -- so I figured maybe just setup the element and pass it the objectmanager from the form.
I want to do something like this.
$this->add(
array(
'name' => 'user_id',
'type' => 'Application\Form\Element\UserSelect',
'options' => array(
'label' => 'User',
'object_manager' => $this->getObjectManager(),
),
),
);
Or even better just this
$this->add(
array(
'name' => 'user_id',
'type' => 'Application\Form\Element\UserSelect',
'label' => 'User',
),
);
module.config.php
'service_manager' => array(
'aliases' => array(
'doctrine_service' => 'doctrine.entitymanager.orm_default',
),
'initializers' => array(
function ($instance, $sm) {
if ($instance instanceof DoctrineModule\Persistence\ObjectManagerAwareInterface) {
$instance->setObjectManager(
$sm->get('doctrine_service')
);
}
if ($instance instanceof Application\Form\AbstractForm) {
$instance->init();
}
},
),
),
AbstractForm.php
namespace Application\Form;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use Zend\Form\Form as ZendForm;
abstract class AbstractForm extends ZendForm implements ObjectManagerAwareInterface
{
protected $objectManager;
public function setObjectManager(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
public function getObjectManager()
{
return $this->objectManager;
}
}
TestForm.php
namespace Users\Form;
use Application\Form\AbstractForm;
class Login extends AbstractForm
{
public function init()
{
$this->add(
array(
'name' => 'user_id',
'type' => 'DoctrineORMModule\Form\Element\DoctrineEntity',
'options' => array(
'label' => 'User',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Application\Entity\User',
'property' => 'name',
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('is_deleted' => 0),
'orderBy' => array('name' => 'ASC'),
),
),
),
),
);
}
}
Add your initializer and invokables to the getFormElementConfig method of your Module.php:
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
...
public function getFormElementConfig()
{
return array(
'invokables' => array(
'MyForm' => 'Application\Form\MyForm',
),
'initializers' => array(
'ObjectManagerInitializer' => function ($element, $formElements) {
if ($element instanceof ObjectManagerAwareInterface) {
$services = $formElements->getServiceLocator();
$entityManager = $services->get('Doctrine\ORM\EntityManager');
$element->setObjectManager($entityManager);
}
},
),
);
}
Then use the FormElementManager to get te form:
$forms = $this->getServiceLocator()->get('FormElementManager');
$myForm = $forms->get('MyForm');
Finally add your element inside the init method - not the constructor because he will never be aware of the objectManager:
public function init()
{
$this->add(
array(
'name' => 'user_id',
'type' => 'DoctrineORMModule\Form\Element\DoctrineEntity',
'options' => array(
'label' => 'User',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Application\Entity\User',
'property' => 'name',
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('is_deleted' => 0),
'orderBy' => array('name' => 'ASC'),
),
),
),
),
);
}
See a discussion on this setup here.