Url helper with GET parameter in laravel - url

I want to create an url with this format :
domain.com/list?sortBy=number&sortDir=desc
in my View (blade). I'm using this approach which I don't really prefered :
{{ url("list")."?sortBy=".$sortBy."&sortDir=".$sortDir }}
because using
{{ url("list", $parameters = array('sortBy' => $sortBy, 'sortDir' => $sortDir) }}
didn't produce as I hoped. Is there a better way?

Have you tried the URL::route method.
Example Route:
Route::get('/list', array('as' => 'list.index', 'uses' => 'ListController#getIndex'));
Retrieve the URL to a specific route with query string:
URL::route('list.index', array(
'sortBy' => $sortBy,
'sortDir' => $sortDir
));
If your using a closure on the route:
Route::get('/list', array('as' => 'list.index', function()
{
return URL::route('account-home', array(
'sortBy' => 1,
'sortDir' => 2
));
}));

Related

Yii2: Sending params with Anchor as POST request

I try to get POST Variables in my controller from view with:
<?= GridView::widget([
'dataProvider' => $dataProvider_products,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'label'=>'Name',
'format' => 'raw',
'value'=>function ($data) use ($model, $dataProvider_products) {
return Html::a($data['name'],['suppliers_orders/addproduct', 'order' => $model->id, 'product' => $data['id'],
'data-method'=> 'post',
'data-params' => ['dataProvider' => $dataProvider_products],
]);
},
],
'supplier_product_number',
'size',
'price_net',
],
]); ?>
The parameter dataProvider will always be sent with the URL and results in a GET variable. What is wrong, respectively what must be done, that dataProvider will be sent as POST variable?
Part of my controller is:
public function actionAddproduct($order, $product){
// look for GET variable
$request = Yii::$app->request->get('data');
$dataProvider = $request['params']['dataProvider'];
// look for POST variable
$param1 = Yii::$app->request->post('dataProvider', null);
$dataProvider_suppliers_orders_products = $dataProvider;
return $this->actionView($order);
}
First of all you are passing the data-params in the url parameter rather than setting in the options parameter, so yes it will always be sent as query string no matter you pull your hairs off and become bald ¯\_(ツ)_/¯.
Then According to the DOCS
If the attribute is a data attribute as listed in
yii\helpers\Html::$dataAttributes, such as data or ng, a list of
attributes will be rendered, one for each element in the value array.
For example, 'data' => ['id' => 1, 'name' => 'yii'] generates
data-id="1" data-name="yii" and 'data' => ['params' => ['id' => 1,
'name' => 'yii'], 'status' => 'ok'] generates
data-params='{"id":1,"name":"yii"}' data-status="ok"
So, you need to change the anchor to look like
Html::a($data['name'], ['suppliers_orders/addproduct', 'order' => $model->id, 'product' => $data['id']], [
'data' => [
'method' => 'POST',
'params' => ['dataProvider' => $dataProvider_products]
]
]);
But since you are passing the $dataProvider object to the params it aint going to work because it will be changed to [Object Object] but if it is simple text then it will work, otherwise you have to change your approach.
Your complete code for the GridView should look like below
<?=
GridView::widget([
'dataProvider' => $dataProvider_products,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'label' => 'Name',
'format' => 'raw',
'value' => function ($data) use ($model, $dataProvider_products) {
return Html::a($data['name'], ['suppliers_orders/addproduct', 'order' => $model->id, 'product' => $data['id']], [
'data' => [
'method' => 'POST',
'params' => ['dataProvider' => $dataProvider_products]
]
]);
},
],
'supplier_product_number',
'size',
'price_net',
],
]);
?>

Zend 2: Unit tests for form class

I'm just starting using PHPUnit with Zend and need little help to figure out how these tests should work.
I want to test if form return any error message if I do not pass any POST parameters.
The problem is that one field from my form is using Doctrine's DoctrineModule\Form\Element\ObjectSelect
...
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'user',
'attributes' => array(
'id' => 'user-label',
),
'options' => array(
'object_manager' => $em,
'target_class' => 'Application\Entity\User',
'property' => 'username',
'label' => 'User:',
'display_empty_item' => true,
'empty_item_label' => '---',
'label_generator' => function($entity) {
return $entity->getUsername();
},
),
));
...
I get following error:
Fatal error: Call to a member function getIdentifierFieldNames() on null
I tried override this field with mocked object, however Zend doesn't allow objects in type, just class name (string), so this code doesn't work:
public function testIfFormIsValid()
{
$objectSelect = $this->getMockBuilder('DoctrineModule\Form\Element\ObjectSelect')
->disableOriginalConstructor()
->getMock();
$objectSelect->expects($this->any())
->method('getValueOptions')
->will($this->returnValue(array()));
$form = new \AppModuleComment\Form\Comment('form', array(
'em' => $this->em // Mocked object
));
$form->add(array(
'type' => $objectSelect,
'name' => 'user',
'attributes' => array(
'id' => 'user-label',
),
'options' => array(
'object_manager' => $this->em,
'target_class' => 'Application\Entity\User',
'property' => 'username',
'label' => 'User:',
'display_empty_item' => true,
'empty_item_label' => '---',
'label_generator' => function($entity) {
return $entity->getUsername();
},
),
));
$data = array(
'id' => null,
'user' => null
);
$form->setData($data);
$this->assertTrue($form->isValid(), 'Form is not valid');
}
What am I doing wrong? How should I test such code?
It seems you are testing functionality of Zend or Doctrine (or both) and not your own code. When you use libraries you should trust these libraries.
What happens is: Form\Form::add() uses Form\Factory::create() to create from the array an element. Form\Factory::create() uses Form\FormElementManager::get() to get an element from the given type.
Your type is an object and because Form\FormElementManager::get() can not handle objects your script will fail.
It seems you want to test that if post is empty Form::valid() calls ObjectSelect::valid() but this does not verify if the value is null. That's code from Doctrine / Zend not yours. Don't test it.
More interesting it gets when you want to mock the result of an select from within Doctrines ObjectSelect. But that's another question.

ZF2 I would like to pass json string

I would like to pass json to action, something similar to passing simple variable:
/** module.config.php
'mobileapplication-topup' => array(
'type' => 'segment',
'options' => array(
'route' => '/mob/topup[/:voucherID]',
'constraints' => array(
'voucherID' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Mob\Controller\Topup',
'action' => 'index',
),
),
and TopupController.php
public function indexAction()
{
echo ($this->params('voucherID'));
$result = new ViewModel();
$result->setTerminal(true);
return $result;
}
//** no layout //
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent("Error");
return $response;
}
something similar to this, but just a json string instead of voucherID. What kind of constraints should be added to this json variable?
** Is there any way how to POST the form from other domain to ZF2?
I have found solution, but I don't think it is a perfect one...
What I was thinking that there is some way of passing variables using route
mvc.com/controller/param1/param2
and into this for example just pass a json and decode it in one of the controllers...
but at the moment I'm using basing _GET method
mvc.com/controller/param1/param2?"Json"={"p1":"value1","p2":"value2"}

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