ZF2 form on post losing ID - zend-framework2

I cant pass the ID from the view (or from somewhere else). This is the url:
http://zend2.com/users/user-manager/edit/6
The controller :
public function editAction()
{
if ($this->request->isPost()) {
$post = $this->request->getPost();
echo $post->user_id; exit;
$userTable = $this->getServiceLocator()->get('UserTable');
$user = $userTable->getUser($post->id);
$form = $this->getServiceLocator()->get('UserEditForm');
$form->bind($user);
$form->setData($post);
$this->getServiceLocator()->get('UserTable')->saveUser($user);
}
$userTable = $this->getServiceLocator()->get('UserTable');
$user = $userTable->getUser($this->params()->fromRoute('id'));
$form = $this->getServiceLocator()->get('UserEditForm');
$form->bind($user);
$viewModel = new ViewModel(array(
'form' => $form,
'user_id' => $this->params()->fromRoute('id')
));
return $viewModel;
}
And the view:
$form->setAttribute('action', $this->url(NULL,
array('controller' => 'users_manager', 'action' => 'edit')));
$form->setAttribute('method', 'post');
What is the proper way to pass the ID ? I know that i dont pass the ID in the view but i am not even sure that this is right.

I solved it.
$form->setAttribute('action', $this->url(NULL,
array('controller' => 'users_manager', 'action' => 'edit'),null, true));
The 4th parameter for $this->url is "$reuseMatchedParameters", it speaks for itself.

An alternative is :
$options = ['Query' => ['id' => 12]];
echo $this->url('controller' => 'users_manager', 'action' => 'edit', $options);

Related

Cakephp 3 - Create full url

What I like to do is creating a full url.
Controller = 'A'
Action = 'doSomething'
param1 = $id
param2 = $id2
What I currently get is:
mydomain.com/A/doSomething?param1=X&param2=XX
What I want is:
mydomain.com/A/doSomething/X/XX
Code:
$message = 'Test: '. Router::url([
"controller" => "A",
"action" => "doSomthing",
"param1" => $id,
"param2" => $id2,
'_full' => true
]);
$id1 = 'id1';
$id2 = 'id2';
$url= Router::url([
"controller" => "A",
"action" => "doSomething",
$id1,
$id2,
'_full' => true
]);
debug($url);
Outputs:
'http://host/a/do-something/id1/id2'
Try:
public function doSomthing($param1, $param2)
{
#your code here
}

How to pass the paramter values to another controller's action in ZF2

Hello friends I am new in zf2. I am creating an action in controller, all things are working correctly. When the form is valid, i would like to pass some of the values to redirect page. how can i do this? Please help me out.
My controller action is
public function studenteditAction(){
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('manager', array(
'action' => 'students'
));
}
$form = new StudentsForm();
$request = $this->getRequest();
if ($request->isPost()) {
$students = new Students();
$form->setData($request->getPost());
if ($form->isValid()) {
$students->exchangeArray($form->getData());
$table = $this->getServiceLocator()->get('Students\Model\StudentsTable');
$table->profileStudents($students);
return $this->redirect()->toRoute('manager',array('controller'=>'manager','action'=>'student-view','id'=>$id,'status' => 'profile-ready'));
}
}
return array(
'id' => $id,
'form' => $form,
);
}
I am unable to get the passed status value on controller's view.
'status' => 'profile-ready'
Thanks in advance
You need to modify your routing configuration to accept both 'id' and 'status' values.
'manager' => array(
'type' => 'Segment',
'options' => array(
'route' => '/manager[/:id][/:status]',
'defaults' => array(
'controller' => 'Application\Controller\Manager',
'action' => 'studentView',
),
'constraints' => array(
'id' => '[0-9]*',
'status' => '[a-z-]*'
),
),
),
Controller:
public function studentViewAction()
{
$id = $this->params()->fromRoute('id');
$status = $this->params()->fromRoute('status');
return new ViewModel(array('id' => $id, 'status' => $status));
}
View
<?php
echo $this->id;
echo $this->status;
?>
This is how i pass the required values to another controller's action

Zend-Framework 2 pagination join tables

I need to add a pagination in this code:
$select = new \Zend\Db\Sql\Select ;
$select->from('school');
$select->join('school_parent','school.school_parent_id = school_parent.school_parent_id');
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
I tried this example, but I can't do it with the join table.
Anyone can help me?
public function fetchAll($paginated=false)
{
if($paginated) {
// create a new Select object for the table album
$select = $this->getallAlbum();
// create a new result set based on the Album entity
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Album());
// create a new pagination adapter object
$paginatorAdapter = new DbSelect(
// our configured select object
$select,
// the adapter to run it against
$this->tableGateway->getAdapter(),
// the result set to hydrate
$resultSetPrototype
);
$paginator = new Paginator($paginatorAdapter);
return $paginator;
}
$resultSet = $this->tableGateway->select();
return $resultSet;
}
function getallAlbum(){
$sql = new Select();
$sql->from('album')->columns(array('id', 'artist', 'title'))->join('albumcategory', 'album.catId = albumcategory.catId', array('catName' => 'catName'), Select::JOIN_LEFT);
return $sql;
}
Pagination should work fine with joins. This is what I have, similar to an example you provided:
$select = new \Zend\Db\Sql\Select ;
$select->from('school');
$select->join('school_parent','school.school_parent_id = school_parent.school_parent_id');
return new \Zend\Paginator\Paginator(
new \Zend\Paginator\Adapter\DbSelect(
$select,
$this->tableGateway->getAdapter()
)
);
Please post an exact error that you are getting if the above doesn't work.
Thank you for the answer, but i tried your code, but i had this PDOException message:
SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'school_parent_id'
I also tried, to adapat my "join tables" with the example of Rob Allen:
public function fetchAll($paginated=false)
{
if($paginated) {
// create a new Select object for the table album
$select = new \Zend\Db\Sql\Select ;
$select->from('school');
$select->join('school_parent','school.school_parent_id = school_parent.school_parent_id');
// create a new result set based on the Album entity
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new School());
// create a new pagination adapter object
$paginatorAdapter = new DbSelect(
// our configured select object
$select,
// the adapter to run it against
$this->tableGateway->getAdapter(),
// the result set to hydrate
$resultSetPrototype
);
$paginator = new Paginator($paginatorAdapter);
return $paginator;
}
$resultSet = $this->tableGateway->select();
return $resultSet;
}
But the result is the same.
// create a new Select object for the table album
$select = new \Zend\Db\Sql\Select ;
$select->from('school');
$select->join('school_parent','school.school_parent_id = school_parent.school_parent_id');
//change this like the following
// create a new Select object for the table album
$select = $this->yourFunction();
//and define yourFunction like
function youFunction(){
$sql = new Select();
$sql->from('school')->columns(array('schoolid', 'schoolname', 'anotherfield'))->join('school_parent', 'school.school_parent_id= school_parent.school_parent_id', array('schoolName' => 'schoolName'), Select::JOIN_LEFT);
return $sql;
}
Please try the join syntax
$select->from('table1')->join('table2', 'table1 = table2', array('table2.colum_to_return1', 'table2.colum_to_return2'));
Example pagination and sort Url
https://github.com/bigemployee/zf2-tutorial-paginate-sort
Try with another example pagination and sorting
### module_config.php ###
'router' => array(
'routes' => array(
'album' => array(
'type' => 'segment',
'options' => array(
'route' => '/album[/:action][/:id][/page/:page][/order_by/:order_by][/:order]',
'constraints' => array(
'action' => '(?!\bpage\b)(?!\border_by\b)[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
'page' => '[0-9]+',
'order_by' => '[a-zA-Z][a-zA-Z0-9_-]*',
'order' => 'ASC|DESC',
),
'defaults' => array(
'controller' => 'Album\Controller\Album',
'action' => 'index',
),
),
),
),
),
###### AlbumController ###
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Album\Model\Album;
use Album\Form\AlbumForm;
use Zend\Db\Sql\Select;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\Iterator as paginatorIterator;
class AlbumController extends AbstractActionController {
protected $albumTable;
public function indexAction() {
$select = new Select();
$order_by = $this->params()->fromRoute('order_by') ?
$this->params()->fromRoute('order_by') : 'id';
$order = $this->params()->fromRoute('order') ?
$this->params()->fromRoute('order') : Select::ORDER_ASCENDING;
$page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
$albums = $this->getAlbumTable()->fetchAll($select->order($order_by . ' ' . $order));
$itemsPerPage = 10;
$albums->current();
$paginator = new Paginator(new paginatorIterator($albums));
$paginator->setCurrentPageNumber($page)
->setItemCountPerPage($itemsPerPage)
->setPageRange(7);
return new ViewModel(array(
'order_by' => $order_by,
'order' => $order,
'page' => $page,
'paginator' => $paginator,
));
}
}
Add this line to your code:
$select->columns(array(new Expression('DISTINCT school.school_parent_id')));
OR something like this:
$select->join('school_parent','school.school_parent_id = school_parent.school_parent_id', array('sp_id' => 'school_parent_id'));

How to set query parameter with redirect()

I would like to set a query parameter when redirecting. I tried this:
$this->redirect()->toRoute('login/default', array('action' => 'forgotPassword', 'foo' => 'bar'));
It redirects to:
/login/forgotPassword
Instead of where I would like to redirect which is:
/login/forgotPassword?foo=bar
The query parameter belongs to the third parameter of the URL-Methods.
$this->redirect()->toRoute(
'login/default',
array(
'action' => 'forgotPassword'
),
array( 'query' => array(
'foo' => 'bar'
))
)
Plus.
To redirect a "access" or login, form you can use:
if (!$controller->identity()) {
$sm = $controller->getServiceLocator();
$router = $sm->get('router');
$request = $sm->get('request');
$routeMatch = $router->match($request);
$controller->redirect()->toRoute('login', array(),
array( 'query' =>
array('redir' => $routeMatch->getMatchedRouteName() ) ) );
}
Urls will be:
/login/?redir=current-route

dynamic dropdown get in zf2?

I want to put a dropdown in my project which is made in zf2... I wasted all day but I only got a static dropdown, not dynamic. Can anyone help me with this problem??
UserForm.php
$this->add(array(
'name' => 'group_name',
'type' => 'select',
'attributes' => array(
'id'=>'group_name',
'class'=>'large',
'options' => array('1=>php','2'=>'java'),
),
'options' => array(
'label' => '',
),
));
Thanks in advance for your valuabe answer.
Try this:
$this->add(array(
'name' => 'group_name',
'type' => 'select',
'attributes' => array(
'id'=>'group_name',
'class'=>'large',
),
'options' => array(
'label' => '',
'value_options' => array(
'1' => 'php',
'2' => 'java'
),
),
));
This is what i did:
In my constructor for my form
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'color',
'options' => array(
'empty_option' => 'Select a Color',
'value_options' => self::getColors(),
'label' => 'Color',
),
));
In the form class yet, i created this method:
public static function getColors() {
// access database here
//example return
return array(
'blue' => 'Blue',
'red' => 'Red',
);
}
In my view script:
<div class="form_element">
<?php $element = $form->get('color'); ?>
<label>
<?php echo $element->getOption('label'); ?>
</label>
<?php echo $this->formSelect($element); ?>
</div>
Think about it from a abstract level.
You have one Form
The Form needs Data from the outside
So ultimately your Form has a Dependency. Since we've learned from the official docs, there's two types of Dependency-Injection aka DI. Setter-Injection and Constructor-Injection. Personally(!) i use one or the other in those cases:
Constructor-Injection if the dependency is an absolute requirement for the functionality to work
Setter-Injection if the dependencies are more or less optional to extend already working stuff
In the case of your Form, it is a required dependency (because without it there is no populated Select-Element) hence i'll be giving you an example for Constructor-Injection.
Some action of your controller:
$sl = $this->getServiceLocator();
$dbA = $sl->get('Zend\Db\Adapter\Adapter');
$form = new SomeForm($dbA);
That's all for the form. The population now happens inside your Form. This is only an example and may need some fine-tuning, but you'll get the idea:
class SomeForm extends \Zend\Form
{
public function __construct(\Zend\Db\Adapter\Adapter $dbA)
{
parent::__construct('my-form-name');
// Create all the form elements and stuff
// Get Population data
$popData = array();
$result = $dbA->query('SELECT id, title FROM Categories', $dbA::QUERY_MODE_EXECUTE)->toArray();
foreach ($result as $cat) {
$popData[$cat['id'] = $cat['title'];
}
$selectElement = $this->getElement('select-element-name');
$selectElement->setValueOptions($popData);
}
}
Important: I HAVE NO CLUE ABOUT Zend\Db the above code is only for how i think it would work going by the docs! This is the part that would need some optimization probably. But all in all you'll get the idea of how it's done.
In your controller you can do something like below;
On my first example assuming that you have a Group Table. Then we're going to fetchAll the data in group table;
We need the id and name to be display in select options;
public function indexAction()
{
$groupTable = new GroupTable();
$groupList = $groupTable->fetchAll();
$groups = array();
foreach ($groupList as $list) {
$groups[$list->getId()] = $list->getName();
}
$form = new UserForm();
$form->get('group_name')->setAttributes(array(
'options' => $groups,
));
}
OR
in this example the grouplist is hardcoded;
public function indexAction()
{
$groupList = array('1' => 'PHP', '2' => 'JAVA', '3' => 'C#');
$groups = array();
foreach ($groupList as $id => $list) {
$groups[$id] = $list;
}
$form = new UserForm();
$form->get('group_name')->setAttributes(array(
'options' => $groups,
));
}
Then in your view script;
<?php
$form = $this->form;
echo $this->formRow($form->get('group_name'));
?>
Or you can right a controller helper, you may check this link http://www.resourcemode.com/me/?p=327
Just came across the same problem and had to take a look into zf2 source.
Here's a more OOP solution:
Inside the form constructor:
$this->add(array(
'name' => 'customer',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'options' => array(
0 => 'Kunde',
)
),
'options' => array(
'label' => 'Kunde'
)));
inside the controller:
$view->form = new SearchForm();
$customers = $view->form->get('customer')->getValueOptions();
$customers[] = 'Kunde1';
$customers[] = 'Kunde2';
$customers[] = 'Kunde3';
$customers[] = 'Kunde4';
$view->form->get('customer')->setValueOptions($customers);

Resources