Cakephp Pagination is not working? - mysql

I am new to cakephp, My pagination is not working..
My controller code:
$this->paginate = array('Favourite' =>array('limit' => '1','conditions'=>array('user_id'=>$id)));
$cat_data = $this->paginate('Favourite');
$this->set('fav_data',$cat_data);
My view code:
<!---Code for pagination -->
<div>
<?php echo $this->Paginator->prev('', null, null, array('class' => 'pdisable','escape' => false)); ?>
<div class="numbers"><?php echo $this->Paginator->numbers(); ?> Pages: <?php echo $this->Paginator->counter(); ?></div>
<?php echo $this->Paginator->next('', null, null, array('class' => 'ndisable','escape' => false)); ?>
</div>
It is not displaying one result based on the limit i have given.. It displays all the records.

When you are trying to get the paginated recordset using this line in your code:
$cat_data = $this->paginate('Favourite');
You are actually redeclaring the paginate settings a second time, only without the limit or condition specified anymore. You need to use the Paginator Component class with the Paginate settings you declare beforehand.
In your code:
//here your are declaring the paginate settings one time.
$this->paginate = array('Favourite' =>array('limit'=>'1','conditions'=>array('user_id'=>$id)));
//Here you are re-declaring them again, only not with a limit or condition specified. This effectively overwrites the first settings declaration you made.
$cat_data = $this->paginate('Favourite');
$this->set('fav_data',$cat_data);
Change:
$cat_data = $this->paginate('Favourite');
To:
$cat_data = $this->Paginator->paginate('Favourite');
So your controller code should look like:
//declare settings without conditions.
$this->paginate = array(
'limit' => 1
);
//use above settings to pull the paginated results.
//be sure to add the conditions you had in the settings before to the 2nd parameter of the `paginate()` function.
$this->set('fav_data', $this->Paginator->paginate('Favourite', array('user_id' => $id)));

Related

cakephp : getting pagination link in json format

I am developing a REST API using CakePHP and want to implement the Instagram API pagination style which looks something like this:
{
...
"pagination": {
"next_url": "https://api.instagram.com/v1/tags/puppy/media/recent?access_token=fb2e77d.47a0479900504cb3ab4a1f626d174d2d&max_id=13872296",
"next_max_id": "13872296"
}
}
I have not used any authorization or whatever, so the access_token part can be ignored. My main motive is to get the pagination links (jump links preferably) as JSON data, so I can use it in my JSON serialized view. Because the usual code:
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
doesn't work and simply displays the equivalent HTML code.
Is there any way I can get it like the Instagram API?
Thanks to noslone, i have got the answer. here is the final edited code:
$url = 'http://yourapp.com/pages/index/limit:7';
$returnArray = array(
.....
'pagination' => array(
'next_url' => null,
'prev_url' => null
)
);
if($this->Paginator->hasNext()) {
$temp = intval($this->Paginator->current())+1;
$returnArray['pagination']['next_url'] = $url."/page:".$temp;
}
if($this->Paginator->hasPrev()) {
$temp = intval($this->Paginator->current())-1;
$returnArray['pagination']['next_url'] = $url."/page:".$temp;
}
echo json_encode($returnArray);
just two changes : first don't forget to add limit:value" to your url and secondly use intval with the Paginator->current.
Try something as follow
$url = 'http://yourapp.com/pages/index';
$returnArray = array(
.....
'pagination' => array(
'next_url' => null,
'prev_url' => null
)
);
if($this->Paginator->hasNext()) {
$returnArray['pagination']['next_url'] = $url.'/page:'. ($this->Paginator->current()+1);
}
if($this->Paginator->hasPrev()) {
$returnArray['pagination']['prev_url'] = $url.'/page:'. ($this->Paginator->current()-1);
}
echo json_encode($returnArray);
If you want, you can add more named params to the url:
$params['pagination']['next_url'] = $url.'/page:'.$this->Paginator->current()+1.'/order:name/direction:asc';
As far as I know, Paginator helper generates the front-end link, and when you click on it, it will generate next link.
I do not think you can use it directly to form the Instagram alike API.

How to set cakephp radio-button from mysql?

This cakephp form used to edit a mysql record needs to load the state of a radio button from a mysql database.
The mysql payment_type is enum('Account', 'Credit').
All of the other non-radio-button form inputs reload from the database and payment_type is correctly displayed on another form using this:
<?php echo h($purchaseOrder['PurchaseOrder']['payment_type']); ?>
Why doesn't this correctly set the radio-button from payment_type?
$options = array('account' => 'Account', 'credit' => 'Credit');
$attributes = array('legend' => false, 'value' => 'payment_type');
echo $this->Form->radio('payment_type', $options, $attributes);
In your attribute array, you should assign value which you want to keep selected by default .
For example you want account to be selected by default then in value you should assign 'account'. So your final attribute will be:
$attributes = array('legend' => false, 'value' => 'account');

Implement tab view with sorting and pagination in Yii

Am trying to bring a tab view with list , sorting and pagination in Yii. I have 2 tables named service_request and favourites where the datas come from. In that page I need to display the service request and favourites added date and some other fields. I tried to implement it with join , but it is not successfully listing the datas from service request. In my controller action I had added
$criteria = new CDbCriteria;
$criteria->select = 'favourite_notes,s.service_request_id';
$criteria->join = 'LEFT JOIN service_request s ON service_request_id = 1';
$criteria->condition = 'favourite_type = 1';
$data=new CActiveDataProvider('ProviderFavourite',array('criteria'=>$criteria,'pagination'=>array('pageSize'=>1)
));
$this->renderPartial('viewtest', array(
'ModelInstance' => ProviderFavourite::model()->findAll($criteria),
'dataProvider'=>$data,
));
In viewtest I had provided,
$this->widget('zii.widgets.CListView', array('dataProvider'=>$dataProvider,'itemView'=>'view',
'id'=>'request-list',
'template' => ' {items}{pager}',
));
In view page, I had fetched the data
echo $data->service_request;
echo $data->favourite_notes;
All your suggestions are welcome..
You can build your own function for sorting using CDBCriteria
at model side you can orderby and orderById pass through get or post
$criteria=new CDbCriteria;
$criteria->alias='b';
$criteria->order='b.'.$orderById.' '.$orderBy.',b.type asc,b.smallimage desc';
$dataProvider=new CActiveDataProvider($this->tableName(), array(
'criteria' => $criteria,
'pagination'=>array(
'pageSize'=>$limit,
),
));
Now at view side you can do like here Web pager is pagination class and extrapara is array of parameter those need for pagination
$this->widget('application.extensions.WebPager',
array(
'cssFile'=>false,
'pages' => $pagination,
'extraPara'=>$extraPara,
'id'=>'link_pager'
));

How can I insert data from a table from sql into a dropdown list in zend framework 2?

I need to insert multioptions to a dropdown list, options taken from a table from my database.
I created the elements like:
$this->add(array(
'name' => 'company',
'type' => 'Zend\Form\Element\Select',
//'multiOptions'=> $options,
'options' => array(
'label' => 'Company',
),
'attributes' => array(
'style' => "float:right;",
),
));
I want to choose from a dropdown list some values that are in a table in my database. For example I have the entity Contacts and I need to choose for the contact a company that is in a table named companies in the database.
After reading on zend framework's site, I tried using this code:
$params = array(
'driver'=>'Pdo_Mysql',
'host'=>'localhost',
'username'=>'root',
'password'=>'',
'dbname' =>'myDataBase'
);
$db = new \Zend\Db\Adapter\Adapter($params);
$sql= new Sql($db);
$select = $sql->select();
$select ->from('companies')
->columns(array('id','company_name'))
->order(" 'company_name' ASC");
I also read on some other sites that I could use a function:
$options = $sql->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');
but it seems it doesn't exist anymore in Zend Framework 2.
Please guys, give me a hand. If the code isn't good and you have a better idea, please tell me.
Thanks in advance!
This is just a quick and dirty answer, but i guess it can get you started.
Create a ServiceFactory, this should be done in a separate factory class instead of a closure, but i still use a closure - faster to write ;)
Get the config from the ServiceLocator so you have access to the DB-Params
Create your default SQL Stuff to retriefe the value_options
Populate the value_options using the setValueOptions($valueOptions) function of your given form-element
Module.php getServiceConfig()
return array(
'factories' => array(
'my-form-factory' => function($serviceLocator) {
$form = new My\Form();
$config = $serviceLocator->get('config');
$db = new \Zend\Db\Auth\Adapter\Adapter($config['dbParams']); //or whatever you named the array key
$sql = //do your SQL Stuff
// This is a fake array, it should be your $sql result in the given format
$result = array('value' => 'label', 'value2' => 'label2');
$form->get('elementToPopulate')->setValueOptions($result);
return $form;
}
)
);
SomeController.php someAction()
$form = $this->getServiceLocator()->get('my-form-factory');
return new ViewModel(array(
'form' => $form
));
I hope this gets you started
you have to add that field validation on controller for setting value in it.
$select = $db->select()->where("state_code = ?",$arr["state_code"]);
$resultSet = $cityObj->fetchAll($select);
$cityArr = $resultSet->toArray();
$city_ar = array();
foreach($cityArr as $city){
$city_ar[$city['id']] = $city['company'];
}
$form->company->setMultiOptions($city_ar);
$form->company->setValue($val["company"]);
by using this code drop down of country have the value that are in resultset array ($resultSet).

Google Map V3 Cakephp helper and multiple markers

I am using the Cakephp Google Map V3 Helper. I can get the google map to show up but the markers do not. Here is my view code:
<?php
echo $this->GoogleMapV3->map();
foreach ($allcondos as $condo) {
$options = array(
'lat' => $condo['Unit']['lat'],
'lng' => $condo['Unit']['lon']
);
$this->GoogleMapV3->addMarker($options);
}
?>
I know that if I just tell the app to echo out my $condo['Unit']['lat'] or ['lon'] it will do so in the foreach loop (so it is pulling my data). What I don't know how to do is how to write the code for the $options array. I have also tried this:
foreach ($allcondos as $condo) {
$lat=$condo['Unit']['lat'];
$lon=$condo['Unit']['lon'];
$options = array(
'lat' => $lat,
'lng' => $lon
);
$this->GoogleMapV3->addMarker($options);
}
How do I write this correctly?
A couple easy steps to get this to work:
Download
Download from https://github.com/dereuromark/cakephp-google-map-v3-helper and place the GoogleMapV3Helper.php file in /app/view/helper/GoogleMapV3Helper.php.
Load Helper
Either modify your appcontroller so that the top of it reads like the following:
<?php
class AppController extends Contoller{
public $helpers = array('Html','Javascript','GoogleMapV3');
}
?>
Or load it in a single controller by adding it to the helpers array as such:
<?php
class DemoController extends AppContoller{
function map() {
$this->helpers[] = 'GoogleMapV3';
# rest of your code
}
}
?
Include Scripts
Include Jquery in your header. Include the following as well:
<?php
echo '<script type="text/javascript" src="'.$this->GoogleMapV3->apiUrl().'"></script>';
?>
Create Map Container
Put this in your view where you want your map to appear. Feel free to modify the properties of the div.
<?php echo $this->GoogleMapV3->map(array('div'=>array('id'=>'my_map', 'height'=>'400', 'width'=>'100%'))); ?>
Note: you can change the default position of the map by including more options than just 'div':
<?php echo $this->GoogleMapV3->map(array('map'=>array(
'defaultLat' => 40, # only last fallback, use Configure::write('Google.lat', ...); to define own one
'defaultLng' => -74, # only last fallback, use Configure::write('Google.lng', ...); to define own one
'defaultZoom' => 5,
),'div'=>array('id'=>'my_map', 'height'=>'400', 'width'=>'100%'))); ?>
Add markers
Can be in a loop or whatever, but this is done in the view after your container is created.
<?php
$options = array(
'lat'=>40.770272,
'lng'=>-73.974037,
'title' => 'Some title', # optional
'content' => '<b>HTML</b> Content for the Bubble/InfoWindow' # optional
);
$this->GoogleMapV3->addMarker($options);
?>
note: only set the 'icon' key in the array if you want to use a custom image. Otherwise, they will not show up.
Include the script for the markers
<?php echo $this->GoogleMapV3->script() ?>
All done!
Alternately, you can use finalize() instead of script() if you do not want to echo the javascript right away, but write it to the buffer for later output in your layout:
<?php $this->GoogleMapV3->finalize(); ?>
See http://www.dereuromark.de/2010/12/21/googlemapsv3-cakephp-helper/ for details.