CakePHP pagination and the get parameters - php

I have a problem with the pagination in my search page.
When a user search something I have a url like domain.com/search/?s=keyword
but paginator gives me links like domain.com/search/page:x,
so in the next and prev and numbers page the get parameter is lost. I need to configure paginator to get links like domain.com/search/page:x/?s=keyword
But I can't do this.
I need to know how to configure
$paginator->options();
$paginator->next();
$paginator->prev();
$paginator->numbers();
to get the needed efect.
Thanx.

create the options array
$options = array(
'url'=> array(
'controller' => 'posts',
'action' => 'search',
'?' => 'keyword='.$keyword
)
);
set it to the helper
$paginator->options($options)
and then you can use the paginator helper while retaining the GET variables.
hope that it helped :)
to make it easier you can putl $paginator options in your view or .ctp file
$this->Paginator->options['url']['?'] = $this->params['ur];
then put the value that you want :)

To pass all URL arguments to paginator functions, add the following to your view:
Plain Text View
$paginator->options(array('url' => $this->passedArgs));
That's it.
See
http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html

I used Matyas solution, but for $keyword I did like this:
$queryString = explode('?', $_SERVER['REQUEST_URI']);
$options = array('url'=> array('controller' => 'post', 'action' => 'search', '?' => $queryString[1]));

use statement in your view for pass parameters while pagination
$paginator->options(array('url' => $this->passedArgs));
this is simplest way to pass parameters.
Some time $this->passedArgs not working at that time pass static value at there and try with that static value.
$paginator->options(array('url' => array('a', 'b')));

Check this comment.
I used it, it works fine.
in app_controller file:
function _paginatorURL() {
$passed = "";
$retain = $this->params['url'];
unset($retain['url']);
$this->set('paginatorURL',array($passed, '?' => http_build_query($retain)));
}
function beforeFilter()
{
$this->_paginatorURL();
}
in views file:
<?php $paginator->options = array( 'url' => $paginatorURL );?>
Hope it helps.

Basically you can do it like this:
function list_results($keywords)
{
$data = $this->paginate('Posts', array('Post.title LIKE' => '%'.$keywords.'%'));
}

I know this is old but found a simple solution that works for me. Add following in view file -
$paginator->options(array('url' => array_merge($this->passedArgs,
array('?' => ltrim(strstr($_SERVER['QUERY_STRING'], '&'), '&')))));
Found it here

$this->Paginator->options['url']['?'] = ['key' => $this->params['url']['value']];

Related

Remove array element with YiiMongoDbSuite

I have some code that should be deleting a record from an embedded MongoDB document.
Here is the code:
public function actionDeleteSaved()
{
$savedLink = $_POST['savedLink'];
$userId = Yii::app()->user->getId();
$current = SaveLink::model()->findByPk($userId);
if(in_array($savedLink, $current->links))
{
array_slice($current->links, $savedLink);
$current->save();
}
}
This is what is passing the data to the controllers action method:
echo CHtml::ajaxButton(
'delete',
Yii::app()->createUrl("dashboard/index/deletesaved"),
array( // ajax options
'type' => 'POST',
'context' => "js:this",
'data' => array(
'savedLink' => $savedLink
)
),
array( //html options
'class'=>'deleteSaved'
)
);
This is what renderPartial looks like:
$this->renderPartial('_deleteSaved', array('savedLink'=>$s));
What I want being posted is being posted correctly but I'm not sure if it's communicating with the Controller and passing the data through or if my code for removing the data from the database is correct.
Any help would be greatly appreciated, thanks.
The problem is with array_slice part. As specified in php docs array slice does not modify array parameter.
Use array_splice instead (it modifies passed array param) and array_search to get key:
if(in_array($savedLink, $current->links))
{
$key = array_search($savedLink, $current->links);
array_splice($current->links, $key, 0);
$current->save();
}
NOTE: If $current->links is embedded documents (objects) array, you might have to find $key and check if is in array some other way.

Attaching condition to find() in controller

i've been trying to learn more about how to have fat models and skinny controllers the right way, because before my models would have basically no code and i'm trying to change that. My function works, but now i'm trying to combine two find() queries that look almost exactly the same except one of them has a simple condition.
My model looks something like this:
function pieChart() {
//Get Data for PieChart
$this->RecordDrug->virtualFields['sum'] ='COUNT(*)';
$records = array();
$records=$this->RecordDrug->find('list',
array('fields' => array( 'Drug.drug', 'sum'),
'contain' => array( 'Drug', 'Record' ),
'group' => 'Drug.Drug'
));
$this->set('output',$records);
return $records;
}
I will have two controllers using this. One of them will use this code as is, just simply call the pieChart() function. The other controller will have to see a condition that only selects the users entries. So
'conditions' => array('Record.user_id' => $this->Auth->user('id'))
How do I go about this the right way? I think i'm having trouble with this because my OOP knowledge is pretty limited. If anyone has any examples or resources that can help me make my find() functions more efficient and streamlined, i'd really appreciate it.
I done that kind of things very simple:
public function myQuery($conditions = null) {
$this->virtualFields['sum'] ='COUNT(*)';
$result = $this->find('all', array('conditions' => $conditions,
'fields' => array('Drug.drug', 'sum'),
'contain' => array('Drug','Record'),
'group' => 'Drug.Drug'
));
return $result;
}
Now you can call this with your argument:
$conditions = array('Record.user_id' => $this->Auth->user('id'));
$data = $this->RecordDrug->myQuery($conditions);
Or without it:
$data = $this->RecordDrug->myQuery();
Note that in this case you need to put myQuery() in to RecordDrug model and you need to use 'all' instead of 'list', because 'list' doesn't support contain option.
So now if you have additional conditions - you just need to pass it in the argument. If you leave it null - it do the query without the conditions statement.

Cakephp ClassRegistry::init

I have this code:
$userObj = ClassRegistry::init('User');
$userObj->contain();
$conditions = "User.studio_id = '".$studioID."' AND User.usergroup_id = 5";
$studioAdmin = $userObj->find($conditions);
The one that is causing the error is this line:
$studioAdmin = $userObj->find($conditions);
When I say error, it does not print anything or any warning of error, it just stops the code below it, I noticed that one because when I try to echo a code above it, it prints it, but when I try to echo a code below it, it does not print anything,
What is the problem here. Your help will be greatly appreciated! Thanks! :)
The better practice way of loading models in components is to go via the controller, and use loadModel()
In your component, set up the initialize()
function initialize($controller, $settings) {
$this->Controller =& $controller;
}
Then in your component function, use loadModel to load the model
$this->Controller->loadModel('Modelname');
$this->Modelname->save($data);
and also for find condition
$users = $this->Modelname->find('all', array(
'conditions' => array(
'User.studio_id' => $studioID,
'User.usergroup_id' => 5
)
));
You should be doing this:
$studioAdmin = $userObj->find('all', array( 'conditions' => $conditions ) );
Do you have PHP error messaging turned on? Did you check your logs to see what the specific error is?
Also, by cake standards, it is better to build your conditions clause this way:
$conditions = array(
"User.studio_id" => $studioID,
"User.usergroup_id" => 5"
);

codeigniter array

How can I grab this data and increment it in Codeigniter?
$_SESSION['cart'][$_GET[id]]++;
because CI destroys the $_GET array, you can do this
$_SESSION['cart'][$this->uri->segment(3)]++;
where 3 is the URL segment of the ID. But I would look in to the shopping cart class as recommended by Malachi.
from the docs ~
$data = array(
'rowid' => 'b99ccdf16028f015540f341130b6d8ec',
'qty' => 3
);
$this->cart->update($data);
It's frowned upon, but if you really want to use the $_GET var you can always do the following:
parse_str($_SERVER['QUERY_STRING'],$_GET);
I would stick with using URI segments as shown by Ross or have the 'id' supplied as a parameter in the controller function.
maybe like this...
$cart = $this->session->userdata('cart');
$cart[$this->uri->segment(3)];
$this->input->get() is no longer messed with, so GET away.
You can do in this way.
By passing variable in your controller function, Your controller function will look like this
function my_function($id='')
{
//Your code goes here
$my_cart = $this->session->userdata('cart');
$my_data = $my_cart[$id];
}

Passing additional parameters to the Zend partialLoop View Helper

In a Zend view I can apply a partial template to an iterable element as follows:
$this->partialLoop('template.phtml', $iterable);
However inside the template, only the elements of the $iterable are available, is there another way of passing extra data to the partial?
I use
$this->partialLoop('template.phtml', array(
'data' => $iterable,
'otherVariable' => $otherVariable
);
Warning & Edit:
To be completly honest, I made a mistake. I guess that the code I proposed won't work. I mistaken it for the partial() helper. It won't work because of this part of the helper's class:
foreach ($model as $item) {
// increment the counter variable
$this->partialCounter++;
$content .= $this->partial($name, $module, $item);
}
It will iterate over the whole array instead of the "data" key. I don't get how the answer could be accepted :D Thanks to Nikolaus Dulgeridis for pointing that out.
You can't even post any extra data through $this->view because the point of partial is that it creates "clean" view instance - so that the assigned variables won't collide with your existing variables.
Possible options
- Extend the view helper with methods to set custom variables
- Iterate the array and reformat it to
array(
array('data' => $item1, 'id' => 1, 'totalCount' => 10) ,
array('data' => $item2, 'id' => 2, 'totalCount' => 10) ,
array('data' => $item3, 'id' => 3, 'totalCount' => 10) ,
)
- Use Registry to store the values.
Zend_Registry::set('partialLoopCount', $count);
$this->partialLoop($viewScript, $data);
- Dump partialLoop and use partial() instead
I prefer this solution.
$count = count($data);
foreach ($data as $key => $value) {
echo $this->partial($viewScript, array('item' => $value, 'position' => $key, 'count' => $count));
}
Inside the partial, you can access all of your view variables with:
$this->partialLoop()->view->myVariable
where myVariable is a normal view variable ($this->view->myVariable in the controller or
$this->myVariable in the view, which it's actually the same thing).
Basically, you retrieve the PartialLoop() object, then the view which called it, and then the variable itself.
This, though, will probably impact performance (and I don't think it's really MVC friendly...)
But, hey: it works. :)
An example here:
Hardcode.nl == Joris Osterhaus
Later I found (insert in partial):
$this->getHelper('PartialLoop')->view->otherVariable;
You can access parent view variables by this way :
$this->ViewModel()->getCurrent()->getVariable('parentVariable');
Found at http://blog.dossantos.com.au/how-to-access-parent-view-variables-from-a-partial-loop-in-zf2
In controller
$this->view->otherVariable = 'otherVariable';
In "partial file" - template.phtml
$this->otherVariable
(ZendFramework-1.11.4-minimal)

Categories