cakephp 2.2.2 pagination search condition - cakephp

I am trying to add pagination in CakePHP 2.x with condition search in a form. However, in the View it doesn't give the next page with my condition. Here is my code:
Controller
public function result($palabraclave = null)
{
$this->layout = 'tempart';
$this->paginate = array(
'limit' => 5,
'order' => array(
'Articulo.created' => 'desc'),
'conditions'=>array("titulo like ?"=>"%".$this->data['Paginas']['palabraclave']."%")
)
$data = $this->paginate('Articulo');//Consulta a la base de datos
$this->set(compact('data'));
}
If I click "next" to see the next page result of the search, it doesn't pass on the pagination condition from page 1 to page 2. :(
View:
<div style="display: inline-block; width:70%;" id="test">
<?php foreach ($data as $da): ?>
<br />
<article>
<?php echo $this->Html->image('article_preview/mini_'.$da['Articulo']['imagen'], array('alt' => 'Hospital-Excel'))?>
<div style="text-align:left;">
<?php echo $this->Html->link("<h6 class='artnombre'>".$da['Articulo']['titulo']."<h6>", array('class'=>"artnombre",'action'=> 'articulo',$da['Articulo']['id']),array('escape' => false)); ?>
</div>
<br />
<p>
<?php echo $da['Articulo']['descripcion']; ?> <?php echo $this->Html->link('Read more ....', array('action'=> 'articulo',$da['Articulo']['id'])); ?>
<h5></h5>
</p>
<div class="puntoshorizontal" style="clear"></div>
</article>
<?php endforeach; ?>
<div style="text-align:center">
<?php
// Shows the page numbers
// Shows the next and previous links
echo $this->Paginator->prev('« Back', null, null, array('class' => 'disabled')) . " |";
echo $this->Paginator->numbers(). "| ";
echo $this->Paginator->next('Next »', null, null, array('class' => 'disabled'));
echo "<br />";
echo $this->Paginator->counter();
// prints X of Y, where X is current page and Y is number of pages
?>
</div>
</div>

a way to persist your search params on each page you should do the following:
After you post data, in your method you have $this->data['Paginas']['palabraClave'] then save it the the session. So in each subsequent call to /resultados/pag1,2,..n you get the value of palabra clave from the session.
Finally you would get something like:
public function resultados(){
$conditions = array();
if($this->Session->check('conditions')){
$conditions = $this->Session->read('conditions');
}
if(isset($this->data)){
$conditions = array("titulo LIKE" => "%".this->data['Paginas']'palabraclave']"%",));
//save to the session
$this->Session->write('conditions',$conditions);
}
$data = $this->painate('Articulo',$conditions);
$this->set('data');
}
This may need some adjust but the idea I think is clear.

Set your paginate conditions when calling the paginate method, like this:
$data = $this->paginate('Articulo', array(
"titulo LIKE" => "%" . $this->data['Paginas']['palabraclave'] . "%",
));
as opposed to in the paginate property.

this is example:
1: pass all URL arguments to paginator functions
$this->Paginator->options(array('url' => $this->passedArgs));
2: Common mistake: not keep condition search with paginate
if($this->data){
$this->passedArgs = array(
'name' => $this->data[‘User’]['name']
);
}else{
if(isset($this->passedArgs['name'])){
$this->data[‘User’]['name'] = $this->passedArgs['name'];
}else{
$this->data[‘User’]['name'] = ;
}
}

Related

simple blog with croogo

I is not What is the problem, I made a simple blog in Croogo, the problem is it is not adding or modifying or delete, because Arabic language ??
function add in controller
`public function admin_add() {
$this->set('title_for_layout', __('Add Part'));
if (!empty($this->request->data)) {
$this->Part->create();
if ($this->Part->save($this->request->data)) {
$this->Session->setFlash(__('The Part has been saved'), 'default', array('class' => 'success'));
$this->redirect(array('action' => 'index'));//, $this->Part->id));
} else {
$this->Session->setFlash(__('The Part could not be saved. Please, try again.'), 'default', array('class' => 'error'));
}
}
}`
=>
model
`class Part extends AppModel {
public $name = 'Part';
var $belongsTo = array(
'Market' => array(
'className' => 'Market',
'foreignKey' => 'market_id',
)
);
protected $_displayFields = array(
'id',
'num_part',
'prix_part',
'prop_Pledge',
'prix_Pledge',
);
}
`
add view
<?php $this->extend('/Common/admin_edit'); ?>
<?php echo $this->Form->create('Part');?>
<fieldset>
<div class="tabs">
<ul>
<li><span><?php echo __('Part'); ?></span></li>
<?php echo $this->Layout->adminTabs(); ?>
</ul>
<div id="role-main">
<?php
echo $this->Form->label('num_part', 'العدد : ');
echo $this->Form->input('num_part',array('label' => false ));
echo $this->Form->label('prix_part', 'االمبلغ : ');
echo $this->Form->input('prix_part',array('label' => false ));
echo $this->Form->label('prop_Pledge', 'إقتراح التعهد : ');
echo $this->Form->input('prop_Pledge',array('label' => false ));
echo $this->Form->label('prix_Pledge', 'مبلغ التعهد : ');
echo $this->Form->input('prix_Pledge',array('label' => false ));
?>
</div>
<?php echo $this->Layout->adminTabs(); ?>
</div>
</fieldset>
<div class="buttons">
<?php
echo $this->Form->end(__('Save'));
echo $this->Html->link(__('Cancel'), array(
'action' => 'index',
), array(
'class' => 'cancel',
));
?>
</div>
message error : The requested address was not found on this server.
I don't think it is because of Arabic language because when you do :
echo $this->Form->label('prop_Pledge', 'إقتراح التعهد : ');
The second parameter is a text. I don't know which Cake version you're using but I think that the first field should be Part.prop_Pledge (Cake v3).
I suggest you to try to use debug() and exit to see where is the real problem or try to put remove arabic characters to see if this is the reason of you're problem.
Just a question where is your $this->Form->create() in view ?
line added to the database successfully but does not retoure to index
it displays an error message
Could you print the message error hello21 please ?
Hope this will help you.

how give pagination to controllers

in controller
public function home($id=null){
$this->loadModel('Usermgmt.User');
if(isset($id)){
$groups=$this->User->findAllByuser_group_id($id);
$this->set('groups', $groups);
} else{
echo 'no id';
$users=$this->User->find('all');
$this->set('users', $users);
}
}
here i geeting value which matches the user_group_id and prints here i am geeting more then 10 users but i need to print only 5 on one page and need to give pagination how to give pagination here
view
<?php
if (!empty($groups)) {
// print_r($groups);
$sl=0;
foreach ($groups as $row1) {
//print_r($row1);
$sl++; ?>
<div style="width:100%;display:inline-block;">
<div style="float:left">
<?php
//echo $row1['id'];
echo $this->Html->link($this->Html->image('../files/user/photo/'.$row1 ['User']['photo_dir'].'/'.$row1 ['User']['photo'], array('width' => '180', 'height' => '180')),
array('controller'=>'Profiles','action'=>'index',$row1['User']['id']),
array('escape' => false));
?>
</div>
<div>
<?php echo h($row1['User']['first_name'])." ".h($row1['User']['last_name'])."</br>";
echo h($row1['User']['username'])."</br>";
echo h($row1['User']['email'])."</br>";
echo h($row1['User']['mobile'])."</br>";
echo h($row1['UserGroup']['name'])."</br>";
?></div>
<div style="clear:both;"></div>
</div>
<?php }
}?>
Call paginate
The equivalent paginate call to this:
$groups=$this->User->findAllByuser_group_id($id);
(incidentally - that should be findAllByUserGroupId) is this:
$groups = $this->paginate('User', array('user_group_id' => $id));
Changing default options
To achieve:
i need to print only 5 on one page
Modify the paginate property of your controller, e.g.:
class UsersController extends AppController {
public $paginate = array('limit' => 5);
function home($id = null) {
...
$conditions = array();
if ($id) {
$conditions['user_group_id'] = $id;
}
$groups = $this->paginate('User', $conditions);
...
}
}
View Modifications
In your view, the pagination helper, and the pagination information will automatically be available by calling paginate as shown above. To get pagination links use the pagination helper:
echo $this->Paginator->numbers();
See the documentation for more information and examples of using pagination.
As in cakephp pagination can be done using pagination helper of cakephp
In controller action use $this->paginate . From Model return all parameters like fields, conditions and so on in array format , so now in controller you will write
$data = $this->ModelName->functionname();
$currentPage = isset($_REQUEST['currentpage']) ? $_REQUEST['currentpage'] : '';
$this->paginate = array(
'fields' => $data['fields'],
'conditions' => $data['conditions'],
'order' => $data['order'],
'page' => $currentPage,
'limit' => 25
);
$currentPage is fetched from $_REQUEST['currentpage'];
and finally pass this data to Paginate Helper
$data = $this->paginate('ModelName');
Now in view you will use Pagination functions as shown below
<?php echo $this->Paginator->prev('revious'); ?>
<?php echo $this->Paginator->numbers(); ?>
<?php echo $this->Paginator->next('Next'); ?>

Loop to display one product / several products by sku on Woocommerce?

I'm attempting to display one or more specific product(s) on my home page on Woocommerce, in a very simple fashion :
name of the product;
short description of the product;
price of the product;
quantity selector;
add to cart button;
Now, i've created a custom loop for doing so:
<?php
$args = array(
'post_type' => 'product',
'sku' => 'lundivegetarien',
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
echo the_title();
echo woocommerce_template_single_excerpt();
echo woocommerce_template_single_price();
echo woocommerce_template_single_add_to_cart();
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
Main problem here is that this loop displays all my products, irrespectively of the sku i'm trying to call. I would like to be more specific, and be able to choose to display one or several products i'd call by their specific sku.
What am i doing wrong?
Any pointers?
Help appreciated!
Sorted out the problem myself eventually, so dumb i was! Just turned to using categories and it works pretty fine!
Here's the updated code in cas anybody needs it!
<?php
$args = array( 'post_type' => 'product', 'product_cat' => 'name_of_the_category', 'posts_per_page' => 1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product;
?>
<p>
<?php
the_title();
?>
</p>
<?php
echo woocommerce_template_single_excerpt();
echo $product->get_price_html();
?>
<div class="order_form close">
<p>
<?php
woocommerce_template_loop_add_to_cart( $loop->post, $product );
?>
</p>
</div>
<br>
<?php
endwhile;
?>
Hope this will help someone!

CakePHP 2.1 + AJAX Search / JsHelper

I try to create an Ajax search with CakePHP using the JsHelper. The Ajax request triggers but it never returns values:
Search form (find_entries.ctp):
<?php echo $this->Form->create('Entry');?>
<?php echo $this->Form->input('title', array('div' => false, 'empty', 'label' => false, 'placeholder' => 'Search'));?>
<?php echo $this->Js->submit('Upload', array(
'before'=>$this->Js->get('#checking')->effect('fadeIn'),
'success'=>$this->Js->get('#checking')->effect('fadeOut'),
'update'=>'#choose_options')
)
;?>
<?php echo $this->Form->end();?>
Controller:
public function find_entries(){
if(!empty($this->request->data)){
$entries = $this->Entry->find('all', array('conditions' => array('Entry.title' => $this->request->data['Entry']['title);
$this->set('entries', $entries);
if($this->RequestHandler->isAjax()){
$this->render('entries', 'ajax');
}
}
}
Partial to render (entries.ctp)
<div id="entries">
<?php foreach ($entries as $entry) :?>
<?php echo $entry['Entry']['title']; ?>
<?php endforeach ;?>
What goes wrong here? thanks!
have you created any div tag with id choose_options to render the ajax result? If not create a div tag like this in the view file.
<div id="choose_options"></div>

cakephp: how to render related models in the view

My objective is to display records for a related child model (once removed) in the view. My problem is that I receive a 'Notice (8): Undefined index:' error message when I try to output the following query.
Tournaments have many tournamentDetails, and tournamentDetails have many updates. I'm trying to display all the updates for each tournamentDetail that is displayed on the tournaments view.
So my question is how to properly resolve the error message and display the updates for each tournamentDetail on the tournaments view page.
My find data in the 'tournaments' controller view action is:
$updates = $this->Tournament->TournamentDetail->Update->find('all', array( 'tournament_details.tournament_id'=> $this->data['Tournament']['id']));
In the view, I have this code.
<?php foreach ($tournament['Update'] as $update): ?>
<h3>Updates</h3>
<h1><?php echo $update ['title']; ?></h1>
<p><?php echo $update ['body']; ?></p>
<hr/>
<?php endforeach; ?>
This is the same 'foreach' code the I use for the other related child records without problem. I did use the debug() function to investigate but didn't see what I was missing.
The output of the $updates array from the debug function looks like this:
Array
(
[0] => Array
(
[Update] => Array
(
[id] => 1
[title] => first round matches start today
[date] => 2010-03-19
[body] => this tournament's first round matches start today.
[tournament_detail_id] => 4
[homeStatus] => no
)
Is there a special way to display records this deep?
As always, thanks in advance.
Paul
Update: Feb 23/11
After some testing the problem I seem to have is finding and passing the correct value to the $updates variable;
To summarize, I want the $updates variable to hold the current 'tournament_details_id'. This will then display the related update records in the 'tournaments' view.
I'm still a beginner and most likely overlooked the obvious.
Here is the model info:
class Tournament extends AppModel {
var $name = 'Tournament';
var $hasMany = array(
'TournamentDetail' => array(
'className' => 'TournamentDetail',
'foreignKey' => 'tournament_id',)
class TournamentDetail extends AppModel {
var $name = 'TournamentDetail';
var $belongsTo = array(
'Tournament' => array(
'className' => 'Tournament',
'foreignKey' => 'tournament_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
class Update extends AppModel {
var $name = 'Update';
var $belongsTo = array(
'TournamentDetails' => array(
'className' => 'TournamentDetails',
'foreignKey' => 'tournament_detail_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Controller data:
class TournamentsController extends AppController
function view($slug = null) {
if (!$slug) {
$this->Session->setFlash(__('Invalid Tournament.', true));
$this->redirect(array('action'=>'index'));
}
$this->Tournament->recursive = 1;
$tournament = $this->Tournament->findBySlug($slug);
$updates = $this->Tournament->TournamentDetail->Update->find('all', array('conditions' => array( 'tournament_details_id' => $this->data['TournamentDetails']['id'] )));
$this->set(compact('tournament','updates', $updates ));
Tournament view. This is display the 'tournament details' and (ideally) related tournament detail 'updates'
<h2><?php echo $tournament['Tournament']['name']; ?></h2>
<?php foreach ($tournament['TournamentDetail'] as $tournamentDetail): ?>
<h1><?php echo $tournamentDetail ['title']; ?></h1>
<p><?php echo $tournamentDetail ['body']; ?></p>
<?php endforeach; ?>
<?php foreach ($updates['Update'] as $update): ?>
<h4>Update: <?php echo $update ['date']; ?></h4>
<p> <?php echo $update ['Update'] ['title']; ?></p>
<p><?php echo $update ['Update'] ['body']; ?></p>
<?php endforeach; ?>
I've tested this by adding in the tournament details 'id' as an integer and it pulls up the correct 'update' record. However I seem to have problems configuring the find operation to do the same.
As always I appreciate the help.
Thanks
Paul
Based on your debug output, it seems that your $tournaments variable consists of an array (instead of the associative array) so you might want to use the foreach to access each of those elements:
foreach ($tournaments as $update):
?>
<h3>Updates</h3>
<h1><?php echo $update ['Update']['title']; ?></h1>
<p><?php echo $update ['Update']['body']; ?></p>
<hr/>
<?php endforeach; ?>
It appears that you be using the wrong variable, you talk about the $updates variable but you're using the $tournament variable in your view.
<?php foreach ($updates['Update'] as $update): ?>
<h3>Updates</h3>
<h1><?php echo $update ['title']; ?></h1>
<p><?php echo $update ['body']; ?></p>
<hr/>
<?php endforeach; ?>
Additionally you haven't posted the whole controller method, which includes that find but you might not have sent the data to the view yet either
$this->set(compact('updates'));

Resources