$map=$this->Sessiondetails->find("all");
$this->set("map",$map);
foreach($map as $maps){
echo $maps['Sessiondetails']['latitude'];
}
I want to fetch only 3rd row values . How to do it in cakephp. I am using cakephp 2x.
How would you do it in SQL? Think about it and then use cake syntax
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#retrieving-your-data
$map = $this->Sessiondetails->find(
"all"
array(
'offset' => 2
'limit' => 1
)
);
of course if you want to run a query that retrieves all the records but then just show the 3rd record you can simply do
echo $map[2]['Sessiondetails']['latitude']
You can use 2way
If you use Paginator component you can use this :
$this->paginate = array('limit' => 10);
else :
$map = $this->Sessiondetails->find(
"all",
array(
'offset' => 2
'limit' => 1
)
);
This will work for you, Here you just need to pass the limit..
<?php
$map=$this->Sessiondetails->find("all",array('limit'=>'2,1'););
$this->set("map",$map);
foreach($map as $maps)
{
echo $maps['Sessiondetails']['latitude'];
}
?>
Related
I have encountered a weird problem, where in the Controller is passing a single record from a table, but the View ends up displaying the entire table.
I have extensive logging and am pretty sure, that the Controller is passing a single record via the $this->set().
Controller (ContactsController : show_list)
$arr_contacts = $this->Contact->find(
'all',
array(
'conditions' => array(
'Contact.state_id' => $i_state_id,
'Contact.city'=> $str_city
),
'fields' => array(
'Contact.id',
'Contact.name',
'Contact.city'
),
'recursive' => -1
)
);
$contacts = $arr_contacts;
$this->log ($contacts, 'debug');
$this->set('contacts', $this->paginate());
$this->log(__FUNCTION__." : ".__LINE__, 'debug' );
Output in log:
Debug: Array
(
[0] => Array
(
[Contact] => Array
(
[id] => 504
[name] => Michael
[city] => New York
)
)
)
Debug: show_list : 303
In the view file (show_list.ctp), I have
<div class="contacts index">
<?php echo print_r($contacts);?>
The view file, prints a list of all records from the table. The SQL dump that cakephp displays, shows that additional SQL calls are being made. However, it isn't clear, where those calls are coming from.
The rest of the controllers and actions seem to be working fine, ruling out any corruption issues.
Has anyone encountered a similar situation before? Any pointers?
You pass the output of the paginate() function to your view, which is different from your own find() call.
If you want the same conditions as with your find(). pass them to paginate() (Tip: put your conditions in an array first)
If you do not need Paginate as it seems you don't since you are only getting a single line of entries from Db, then you should rewrite your $this->set() as such:
$this->set('contacts',$contacts);
If you need Paginate (???), then you need to set you entire function as such:
$this->paginate = array(
'conditions' => array(
'Contact.state_id' => $i_state_id,
'Contact.city'=> $str_city
),
'fields' => array(
'Contact.id',
'Contact.name',
'Contact.city'
),
'recursive' => -1
);
$this->log ($this->paginate, 'debug');
$this->set('contacts', $this->paginate());
$this->log(__FUNCTION__." : ".__LINE__, 'debug' );
I am using cakephp 1.3 and i am receiving strange problem with pagination.I have imnplemented pagination for I have working pagination code in more than one controller .But my rest of the controller not showing next and previous button and numbers for pagination is working fine
I am using this code in my view
<?php
if(!empty($zipcodes)){
echo "<div class='pagination'>";
echo #$this->Paginator->prev('« Previous', null, null, array('class' => 'disabled'));
echo #$this->Paginator->numbers();
echo #$this->Paginator->next('Next »', null, null, array('class' => 'disabled'));
echo '<div style="float:right;padding:5px;color:#000">'.$this->Paginator->counter().'</div>';
echo "<div class='clear'></div>";
echo "</div>";
}
?>
And in my controller i have used pagination controller as i am paginating custom query results .I included pagination code in app_model.php.
My ontroller code is
var $paginate = array(
'Zipcode' => array('limit' => 5,
'order' => array('id' => 'desc'),
)
);
my query and operation
$tsql = " SELECT Zipcode.* ".
" FROM zipcodes AS Zipcode ".
" WHERE Zipcode.region_id=0 ";
$conditions = array(
'tsql'=>$tsql,
);
$tmp = $this->paginate('Zipcode',$conditions);
$this->set('zipcodes', $tmp);
can any one point out me what i am doing wrong.??And why pagination is working for only some controller .??? THanks in advance
First, change your paginate in the top of the controller. Remove Zipcode from it. It should just be:
var $paginate = array(
'limit' => 5,
'order' => array('Zipcode.id' => 'desc'),
);
Second, I am not sure what you are trying to accomplish with $tsql, but as far as I know, you cannot pass a SELECT statement as a condition. You need to write ORM specific conditions like this:
$this->paginate = array(
'conditions' => array('Zipcode.region_id' => 0),
);
Then to set zipcodes you can do this:
$this->set('zipcodes', $this->paginate('Zipcode'));
or this
$data = $this->paginate('Zipcode');
$this->set(compact('data'));
As a side note, echo #$this->Paginator->prev should be echo $this->Paginator->prev and all the # should be removed from those lines. That is poor coding practice. I'm not certain if you have the ignore in there for a reason, but it's bad.
I am trying to retrieve the id of a record in my database in the index() method of my cns_controller.php file. I want to use it for a find(). However, the $this->Cn->id is not returning a value, therefore the find() doesn't work either.
$uses = array('Cn', 'Release');
/*check non-null value in released_user_id,
showing Release tab has been signed off*/
$releaseSignedOff = $this->Release->find('all', array(
'conditions' => array('Release.cn_id =' => $this->Cn->id,
'Release.released_user_id !=' => null)
));
(sizeof($releaseSignedOff) > 0) ? $releaseSignedOff = true : $releaseSignedOff = false;
$this->set('releaseSignedOff', $releaseSignedOff);
Any ideas?
Thanks
I ended up not using my index view, instead I looked up the most recent record in my cns database table and redirected to the view view using the returned value as a parameter:
if (!$id) {
$most_recent_change_note = $this->Cn->find('first', array(
'order' => array('Cn.id DESC')
));
$this->redirect(array('controller' => 'cns',
'action' => 'view/'.$most_recent_change_note['Cn']['id']));
}
For the pagination, I ended up using the $neighbors feature of CakePHP:
function get_neighbors($id) {
$neighbors = $this->Cn->find('neighbors', array('field' => 'id',
'value' => $id));
$this->set('neighbors', $neighbors);
}
Then in my view view, I used those values to create links:
<div class="paging">
<?php echo ($neighbors['next']) ? $html->link('<< Prev',
array('controller'=>'cns',
'action'=>'view/'.$neighbors['next']['Cn']['id'])).' | ' : '<< Prev | ';
echo $html->link('Next >>', array('controller'=>'cns',
'action'=>'view/'.$neighbors['prev']['Cn']['id'])); ?>
</div>
Thanks to Charles and Ross for helping me reach this conclusion. :)
Hi I want to be able to generate a list using find so that I can use in select helper. but there is a problem. i want too fetch id,name(first + last). so how can I achieve it. I want first_name and last_name to be joined as name . How can I achieve it.
$this->User->find('all',array('fields' => array('first_name','last_name','id')));
I can't use model filters and callback Please suggest me how can I do it in controllers itself.
I think this can be done using the virtualFields and displayField properties in your model.
In your model, define a virtual field for the full name like this:
public $virtualFields = array(
'full_name' => 'CONCAT(User.first_name, " ", User.last_name)'
);
If you now set displayField to full_name you should be able to get a list of your users with the $this->User->find('list') method which you can use without problems with the Form-helper.
public $displayField = 'full_name';
... or:
public $displayField = 'User.full_name';
The id is fetched automatically.
Another solution is to use Cake's Set::combine to build what you need...
$users = $this->User->find('all',array('fields' => array('first_name','last_name','id')));
$user_list = Set::combine($users, '{n}.User.id', array('{0} {1}', '{n}.User.first_name', '{n}.User.last_name'));
Result will look something like:
array(
[2] => 'First Last',
[5] => 'Bob Jones'
)
Here's the documentation link:
http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::combine
To achieve this first go to the model and add this line
public $virtualFields = array('full_name' => 'CONCAT(first_name, " ", last_name)');
and then go to controller file just use the name "full_name" which you put in virtual fields
$this->User->find('all',array('fields' => array('full_name','id')));
It returns name with combined fields
+1 on Tim's answer, however, if you need an alternative, teknoid wrote a nice article about this a long time ago:
http://nuts-and-bolts-of-cakephp.com/2008/09/04/findlist-with-three-or-combined-fields/
In my case, Set::combine was the way to go, since I had to deal with concatenation of fields in associated models, like:
$bancos_enteros = $this->Financiacion->Banco->find('all', array(
'fields' => array('Empresa.codigo_contable','Empresa.nombre_corto', 'Banco.id'),
'order' => array('Empresa.codigo_contable' => 'asc'),
'recursive' => 1
));
$bancos = Set::combine(
$bancos_enteros,
'{n}.Banco.id',
array(
'{0} {1}',
'{n}.Empresa.codigo_contable',
'{n}.Empresa.nombre_corto'
)
);
returning
array(
(int) 14 => '57200002 Caixa',
(int) 15 => '57200003 Sabadell',
(int) 3 => '57200005 BBVA',
(int) 16 => '57200006 Deutsche Bank',
(int) 17 => '57200007 Popular',
(int) 18 => '57200009 March',
(int) 26 => '57200010 Bankinter',
(int) 4 => '57200011 Santander'
)
While
$this->Financiacion->Banco->Empresa->virtualFields = array(
'codigo_nombre' => 'CONCAT(Empresa.codigo_contable,Empresa.nombre_corto)'
);
$this->Financiacion->Banco->virtualFields['codigo_nombre'] = $this->Financiacion->Banco->Empresa->virtualFields['codigo_nombre'];
$bancos = $this->Financiacion->Banco->find('list', array(
'fields' => array('Banco.id','Banco.codigo_nombre'),
'order' => array('Banco.codigo_nombre' => 'asc'),
'recursive' => 1
)
);
returns a SQL error in a following query if I don't delete the virtual fields first:
unset($this->Financiacion->Banco->Empresa->virtualFields);
unset($this->Financiacion->Banco->virtualFields);
Cake handles pagination of a model with a simple $this->paginate(), but what should I use if I want to paginate a array of values?
The Scenario is like this:
$this->set('sitepages', $this->paginate());
This code in my index() returns an array like
Array
(
[0] => Array
(
[Sitepage] => Array
(
[id] => 13
[name] => Home
[urlslug] => home
[parent_id] => 1
[page_title] => Welcome to KIAMS, Pune
[order] => 1
)
)
[1] => Array
(
[Sitepage] => Array
(
[id] => 26
[name] => About Us
[urlslug] => aboutus
[parent_id] => 1
[page_title] =>
[order] => 2
)
)
[2] => Array
(
[Sitepage] => Array
(
[id] => 27
[name] => Overview of KIAMS
[urlslug] => aboutus/overview
[parent_id] => 26
[page_title] =>
[order] => 2
)
)
I retrieved the same data using $this->Sitepage->find('all') and then performed some manipulations as required and form a array which is very similar to the above one, but the ordering gets changed. I want to paginate this new array and pass it to the view. I tried
$this->set('sitepages',$this->paginate($newarray))
But the data is not getting paginated. Can some one please help with paginating the $newarray in CakePHP?
To paginate in CakePHP you need to pass select conditions to the paginate() call.
Other data manipulation should be done in afterFind(), in your model file.
If you don't need these changes to be done in every single retrieval, you might as well consider creating a new model file pointing to the very same table as the current one, and adding an afterFind() method to that new file.
I've just dealt with this same problem...
I found the only way is to use the paginate() function to handle all the logic, rather than passing it a custom array. However, this isn't as bad as it seems:
$this->paginate = array(
'limit' => 2,
'order' => array(
'Report.name' => 'asc'
),
'conditions' => array(
'Account.id' => $this->foo()
),
);
$reports = $this->paginate();
In this example, I'm paginating Reports - but some Reports will not be included, depending on which Account they belong to (Account has some relationship with Report, hasmany, etc.).
By writing $paginate inside your action, you can use a custom callback for the conditions array. So function foo() can be written in your controller (or shoved to model) and returns an array of valid Account IDs.
I found I could easily rewrite my custom logic in this function - keeping both me and the Cake paginator happy.
Hope that helps!
I'm using cakephp version 1.3 and it seems this one is working:
at controller:
$result = $this->Paginate('Event');
$results = $this->Task->humanizeEvent($result);
$this->set('events', $results);
and it seems to display as a normal paginated array, at the view (setup your pagination in view as normal).
The humanizeEvent function just edits a field on the results array, to make it a sentence based on other fields inside the array, and it seems to work properly.
$this->paginate($newarray) is the wrong way to paginate. The first parameter cannot be an array. It must be a model name. You may want to study pagination setup from the manual. This will order alphabetically:
var $paginate = array(
'limit' => 25,
'order' => array(
'Sitepage.name' => 'asc'
)
);
$this->set('sitepages', $this->paginate('Sitepage'));
I create a component checking the paginator code..
Is not the best thing, but It work for me.....
Controller
$slicedArray = array_slice($fullArray,($page - 1) * $this->PaginatorArray->limit ,$this->PaginatorArray->limit)
$this->params['paging'] = $this->PaginatorArray->getParamsPaging('MyModel', $page, $total,count($slicedArray));
$this->helpers[] = 'Paginator';
Component
<?php
/* SVN FILE: $Id$ */
/**
* Pagination Array Component class file.
* #subpackage cake.cake.libs.view.helpers
*/
class PaginatorArrayComponent {
var $limit = 40;
var $step = 1;
function startup( & $controller){
$this->controller = & $controller;
}
function getParamsPaging($model, $page, $total, $current){
$pageCount = ceil($total / $this->limit);
$prevPage = '';
$nextPage = '';
if($page > 1)
$prevPage = $page - 1;
if($page + 1 <= $pageCount)
$nextPage = $page + 1;
return array(
$model => array(
'page' => $page,
'current' => $current,
'count' => $total,
'prevPage' => $prevPage,
'nextPage' => $nextPage,
'pageCount' => $pageCount,
'defaults' => array(
'limit' => $this->limit,
'step' => $this->step,
'order' => array(),
'conditions' => array(),
),
'options' => array(
'page' => $page,
'limit' => $this->limit,
'order' => array(),
'conditions' => array(),
)
)
);
}
}
?>
There was a bug in find("count") and it returned incorrect count if the query resulted in records for only in group. This has been fixed click here