How to retain search string when using pagination in cakephp 4? - cakephp

I am using cakePHP 4 and I want to paginate my search query. I have users index page and when I search something whose resultant data exceed the defined limit of showing data. Whenever I search something I want the search string to retain in the input box even if I jump to the next page
public function index(){
$this->conditions = array();
if($this->session->check('conditions')){
$this->conditions = $this->session->read('conditions');
}
if ($this->request->is('post')) {
$data = $this->request->getData();
if(!empty($data['search_string'])){
$searchString = trim($data['search_string']);
if($data['search_by'] == 1){
$conditions = array('Users.id LIKE '=> $searchString);
}elseif($data['search_by'] == 2){
$conditions = array('Users.username LIKE '=>'%'.$searchString.'%');
}elseif($data['search_by'] == 3){
$conditions = array('Groups.name LIKE ' => '%'.$searchString.'%');
}
}
$this->conditions = array ($conditions);
$this->session->write('conditions',$this->conditions);
$this->paginate['conditions'] = $this->conditions;
$this->paginate['contain'] = ['Userdetails','Groups'];
$this->paginate['limit'] = 8;
$users = $this->paginate($this->Users);
$this->set('users',$users);
}else{
$this->session->write('conditions',$this->conditions);
$this->paginate['conditions'] = $this->conditions;
$this->paginate['contain'] = ['Userdetails','Groups'];
$this->paginate['limit'] = 8;
$users = $this->paginate($this->Users);
$this->set('users',$users);
}
}

Related

foreach by quantity in laravel

I develop a ticketing system which user have to choose the quantity of ticket category. I want to save the record to database by the total of quantity. But it seems to be failed. I end up only save the record by category id. Here is the result when I try to return it.
and this is my code in controller.
public function ticket_checkout(Request $request)
{
$ctg_id = $request->cat_id;
$price = $request->price;
$name = $request->name;
$qty = $request->qty;
// return count($qty);
$data = [];
$i = 0;
foreach($qty as $item){
if($qty[$i] != 0){
$data[] = [
"ctg_id" => $ctg_id[$i],
"price" => $price[$i],
"qty" => $item,
];
}
$i++;
}
return $data;
Ticket_checkout::insert($data);
// return $qty;
return view('ticket.index', compact('data','qty'));
}
I wonder if I missing something here? I tried to do looping 'for' by quantity inside the 'foreach' but it seems not working too.

Persisting data to database. persist not working

I wrote a controller action that is supposed to add an element (meeting) to the database here it is:
public function newAction(Request $request){
$meeting = new Meeting();
$meetingUser = new MeetingUser();
$project = new Project();
$projectName = "SocialPro";//$request->get('projectName');
echo($projectName);
$users = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findProjectUser($projectName);
//$form = $this->createForm('SocialPro\MeetingBundle\Form\MeetingType', $meeting);
//$form->handleRequest($request);
//if ($form->isSubmitted() && $form->isValid()) {
$userconn = $this->container->get('security.token_storage')->getToken()->getUser();
echo($userconn->getId());
if ($request->isMethod('POST')) {
echo("message form");
$role = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findUserRole($userconn)[0]['role'];
$date = $request->get('date');
if ($role == "PROJECT_MASTER" || $role == "TEAM_MASTER") {
for ($i = 0; $i < count($users); $i++) {
$meetings = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findMeetingUser($users[$i]['id'], $date);
}
if ($meetings == null || count($meetings) == 0) {
$project = $this->getDoctrine()->getRepository('SocialProProjectBundle:Project')->findBy(array("name" = >$projectName));
$meeting->setDescription($request->get('description'));
$meeting->setDate(new \DateTime($request->get('date')));
$meeting->setTime($request->get('time'));
$meeting->setProjectName($request->get('projectName'));
$meeting->setProject($project[0]);
$meetingUser->setMeetings($meeting);
$meetingUser->setUsers($userconn);
var_dump($meetingUser);
$meeting->setMeetingUser(array($meetingUser));
//$project->setMeetings($meeting->getId());
$em = $this->getDoctrine()->getManager();
$em->persist($meeting);
$em->persist($meetingUser);
$em->flush();
// $meetingUser->setUsers($request->get(''));
return $this->redirectToRoute('reunion_show', array('id' = > $meeting->getId()));
}
else {
echo("Membre indisponible");
}
}
else {
echo("Must be MASTER to create meeting");
}
}
return $this->render('SocialProMeetingBundle::ajoutMeeting.html.twig', array('users' = >$users));
// $em = $this->getDoctrine()->getManager();
//$em->persist($meeting);
//$em->flush($meeting);
// return $this->redirectToRoute('meeting_show', array('id' => $meeting->getId()));
//}
//return $this->render('SocialProMeetingBundle:ajouMeeting', array(
// 'meeting' => $meeting,
//'form' => $form->createView(),
//));
}
When I submit the form it gives me a site not available page. I tested it line by line and everything is working perfectly. Turns out the problem is in the
$em->persist($meeting);
And I have no idea how to fix it.
You must call flush immediately after calling persist like so:
$em->persist( $meeting );
$em->flush();
$em->persist( $meetingUser );
$em->flush();
Then it will persist both.

Multiple if statement to update the filed same model or change the records to another model using Cakephp

I am getting array value from the request and my first if statement works great to me, in the case of second if statement its migrating only one row to my salereturn table but i want all the record in the request to be migrate to the salereturn table.
if ($this->request->is('post')) {
$Productsalesrec = !empty($this->request->data['Productsales']) ? $this->request->data['Productsales'] : "";
if (!empty($Productsalesrec)) {
foreach ($Productsalesrec as $Productsales) {
if ($Productsales['status'] == 'MoveToShipment') {
$this->Productsales->id = $Productsales['id'];
$this->request->data['Productsales']['status'] = $Productsales['status'];
$this->Productsales->save($this->request->data);
}
if ($Productsales['status'] == 'Returned') {
$productsalesretArr = array();
$productsalesre = $this->Productsales->find('all', array('conditions' => array('Productsales.product_sales_slno' => $id)));
$this->request->data['Salesreturn']['sales_order_date'] = $productsalesre['Productsales']['sales_order_date'];
$this->request->data['Salesreturn']['product_sale_id'] = $productsalesre['Productsales']['id'];
$this->request->data['Salesreturn']['sales_date'] = $productsalesre['Productsales']['expected_delivery_date'];
$this->request->data['Salesreturn']['product_sales_slno'] = $productsalesre['Productsales']['product_sales_slno'];
$this->request->data['Salesreturn']['price_per_unit_order'] = $productsalesre['Productsales']['sales_price_per_unit_order'];
$this->request->data['Salesreturn']['total_amount'] = $productsalesre['Productsales']['sales_price_per_unit_order'] * $Productsales['tot_unit'];
$this->request->data['Salesreturn']['total_unit'] = $Productsales['tot_unit'];
$this->request->data['Salesreturn']['product_id'] = $Productsales['product_id'];
$this->request->data['Salesreturn']['amount_returned'] = 0;
$this->request->data['Salesreturn']['status'] = 'Returned';
$this->request->data['Salesreturn']['payment_method'] = 'Cash on Delivery';
$this->request->data['Salesreturn']['created_date'] = date('Y-m-d H:i:s');
$this->request->data['Salesreturn']['created_by'] = $this->Auth->user('id');
$this->Salesreturn->save($this->request->data['Salesreturn']);
if ($Productsales['total_unit'] == $Productsales['tot_unit']) {
$this->Productsales->delete($Productsales['id']);
} elseif ($Productsales['total_unit'] >= $Productsales['tot_unit']) {
$this->Productsales->id = $Productsales['id'];
$this->request->data['Productsales']['total_unit'] = $Productsales['total_unit'] - $Productsales['tot_unit'];
$this->Productsales->save($this->request->data);
}
$prodtype = $this->Producttype->find('first', array('conditions' => array('Producttype.id' => $productsalesre['Productsales']['product_type_id'])));
$this->Producttype->id = $prodtype['Producttype']['id'];
$prodquantity = $prodtype['Producttype']['quantity'] + ($Productsales['total_unit'] - $Productsales['tot_unit']);
$prodtotstck = $prodtype['Producttype']['total_unit_stock'] + ($Productsales['total_unit'] - $Productsales['tot_unit']);
$this->Producttype->saveField('total_unit_stock', $prodtotstck);
$this->Producttype->saveField('quantity', $prodquantity);
}
}
$this->redirect(array('action' => 'index'));
}
}
I'm not sure to really understand the problem...
Do you mean this part of code hasn't the wanted behaviour ?
if($Productsales['status'] == 'Returned') {
$this->request->data['Salesreturn']['sales_order_date']=$productsalesre['Productsales']['sales_order_date'];
...
$this->Salesreturn->save($this->request->data['Salesreturn']);
}
Does your condition " $Productsales['status'] == 'Returned' " is the problem ?
may be only one row of your post array has this status.

CakePHP Custom Query Paginator

Currently I am got 2 page require Pagination.
I also do some research such as setting or at model do the custom Query. However the Paginator can't work.
Now I am trying add custom query paginator to index page. (I need to use group by)
I also trying to add custom query paginator to view page. ( I need base on the id)
Controller:
public function index() {
$setting = $this->Paginator->settings = $this->Report->query('
SELECT SUM( seats_occupied ) as totalOccupied, event_date, r.event_date_id
FROM reports r, event_dates ed WHERE r.event_date_id = ed.event_date_id
GROUP BY event_date
');
debug($this->Paginator->paginate());
$this->set('showDate',$setting);
}
public function view($eventDateId = null){
if (!$eventDateId) {
throw new NotFoundException(__('Invalid post'));
}
// We only want single post so we use FindById.
$post = $this->Report->findAllByEventDateId($eventDateId);
// debug($this->Paginator->paginate($post));
if (!$post) {
//if user requet fypcakephp/view without id will throw the not found except
throw new NotFoundException(__('Invalid post'));
}
$setting = $this->Paginator->settings = $this->Report->query("
SELECT *
FROM reports where event_date_id='$eventDateId' order by period asc
");
//array( 'conditions' => array( 'event_date_id' => $post));
debug($setting);
$this->set('viewData', $setting); //Then send this data
}
I also got try do at model custom Query however If I do this way , my view can't get the data I want due to I using "Group By".
//To custom the paginate display the thing you want. (This one return)
//public function paginate($conditions, $fields, $order, $limit, $page = 1,
// $recursive = null, $extra = array())
//{
// $recursive = 0;
//
// // Mandatory to have
// $this->useTable = false;
// $sql = '';
//
//
// $sql .= " select * from reports;";
//
//
//
// $sql .= " SELECT SUM( seats_occupied ) as totalOccupied, event_date,r.event_date_id
// FROM reports r, event_dates ed WHERE r.event_date_id = ed.event_date_id
// GROUP BY event_date; ";
//
//
//
// // Adding LIMIT Clause
//// $sql .= (($page - 1) * $limit) . ', ' . $limit;
//
// $results = $this->query($sql);
//
// return $results;
//}
//public function paginateCount($conditions = null, $recursive = 0, $extra = array())
//{
// $sql = '';
//
// $sql .= "SELECT SUM( seats_occupied ) as totalOccupied, event_date ,r.event_date_id
// FROM reports r, event_dates ed WHERE r.event_date_id = ed.event_date_id
// GROUP BY event_date";
//
// $this->recursive = $recursive;
//
// $results = $this->query($sql);
//
// return count($results);
//}

Problem in executing Cron Jobs

i have done a bidding site in Cake PHP.The main problem I am facing is I need to run CRON JOBS on the server.But I dont' know why it is bugging me.I have craeted a controller called 'deamons' and there 4 different actions of it,which I want to run continuously on the server every minute,so that we can run the Autobidder set by each user of that bidding site.
The Cron Jobs I am setting up are...
curl -s -o /dev/null http://www.domain.com/app/webroot/daemons/bidbutler
curl -s -o /dev/null http://www.domain.com/app/webroot/daemons/extend
curl -s -o /dev/null http://www.domain.com/app/webroot/daemons/autobid
curl -s -o /dev/null http://www.domain.com/app/webroot/daemons/close
and the the controller which is handling all the stuff is attached below....!!!
Please suggest me some solution to this so that
If the experts wants to test it..the URL is www.domain.com/app/webroot
And here is the code...which I am trying to run through the CRONS...!!!
<?php
class DaemonsController extends AppController {
var $name = 'Daemons';
var $uses = array('Auction', 'Setting');
function beforeFilter(){
$email='nishant.nightcrawler#gmail.com';
$secondemail='no-reply#bidoppo.com';
$mess='It works';
//#mail($email, 'Test', $mess, "From: ".$secondemail);
parent::beforeFilter();
if(!empty($this->Auth)) {
$this->Auth->allow('bidbutler', 'extend', 'autobid', 'close');
}
ini_set('max_execution_time', ($this->appConfigurations['cronTime'] * 60) + 1);
}
/**
* The function makes the bid butler magic happen
*
* #return array Affected Auction
*/
function bidbutler() {
$this->layout = 'js/ajax';
$data = array();
$setting = array();
$auctions = array();
// Get the bid butler time
$bidButlerTime = $this->Setting->get('bid_butler_time');
// Get various settings needed
$data['bid_debit'] = $this->Setting->get('bid_debit');
$data['auction_price_increment'] = $this->Setting->get('auction_price_increment');
$data['auction_time_increment'] = $this->Setting->get('auction_time_increment');
$data['auction_peak_start'] = $this->Setting->get('auction_peak_start');
$data['auction_peak_end'] = $this->Setting->get('auction_peak_end');
$expireTime = time() + ($this->appConfigurations['cronTime'] * 60);
while (time() < $expireTime) {
// Formating the conditions
$conditions = array(
'Auction.end_time < \''. date('Y-m-d H:i:s', time() + $bidButlerTime). '\'',
'Auction.closed' => 0,
'Bidbutler.bids >' => 0
);
// Find the bidbutler entry - we get them from the lowest price to the maximum price so that they all run!
$this->Auction->Bidbutler->contain('Auction');
$bidbutlers = $this->Auction->Bidbutler->find('all', array('conditions' => $conditions, 'order' => 'rand()', 'fields' => array('Auction.id', 'Auction.start_price', 'Bidbutler.id', 'Bidbutler.minimum_price', 'Bidbutler.maximum_price', 'Bidbutler.user_id'), 'contain' => 'Auction'));
if(!empty($bidbutlers)) {
// Walk through bidbutler entries
foreach($bidbutlers as $bidbutler) {
if($bidbutler['Bidbutler']['minimum_price'] >= $bidbutler['Auction']['start_price'] &&
$bidbutler['Bidbutler']['maximum_price'] < $bidbutler['Auction']['start_price']) {
// Add more information
$data['auction_id'] = $bidbutler['Auction']['id'];
$data['user_id'] = $bidbutler['Bidbutler']['user_id'];
$data['bid_butler'] = $bidbutler['Bidbutler']['id'];
// Bid the auction
$result = $this->Auction->bid($data);
}
}
}
usleep(900000);
}
}
/**
* The function auto extends auctions and bids for an auto bid if neccessary
*
* #return array Affected Auction
*/
function extend() {
$this->layout = 'js/ajax';
$data = array();
$setting = array();
$auctions = array();
$data['bid_debit'] = $this->Setting->get('bid_debit');
$data['auction_price_increment'] = $this->Setting->get('auction_price_increment');
$data['auction_time_increment'] = $this->Setting->get('auction_time_increment');
$data['auction_peak_start'] = $this->Setting->get('auction_peak_start');
$data['auction_peak_end'] = $this->Setting->get('auction_peak_end');
$data['isPeakNow'] = $this->isPeakNow();
$expireTime = time() + ($this->appConfigurations['cronTime'] * 60);
while (time() < $expireTime) {
// now check for auto extends
$auctions = Cache::read('daemons_extend_auctions');
if(empty($auctions)) {
$auctions = $this->Auction->find('all', array('contain' => '', 'conditions' => "(Auction.extend_enabled = 1 OR Auction.autobid = 1) AND (Auction.start_price < Auction.minimum_price) AND Auction.winner_id = 0 AND Auction.closed = 0"));
Cache::write('daemons_extend_auctions', $auctions, '+1 day');
}
if(!empty($auctions)) {
foreach($auctions as $auction) {
// lets see if we need to extend the auction
$endTime = strtotime($auction['Auction']['end_time']);
$extendTime = time() + ($auction['Auction']['time_before_extend']);
if($extendTime > $endTime) {
// lets see if autobid is enabled
// autobid will place a bid by a robot if another user is the highest bidder but hasn't meet the minimum price
if($auction['Auction']['autobid'] == 1) {
if($auction['Auction']['extend_enabled'] == 1) {
// lets only bid if the limit is less than te autobid limit when the autobid limit is set
if($auction['Auction']['autobid_limit'] > 0) {
if($auction['Auction']['current_limit'] <= $auction['Auction']['autobid_limit']) {
$this->Auction->Autobid->check($auction['Auction']['id'], $auction['Auction']['end_time'], $data);
}
} else {
$this->Auction->Autobid->check($auction['Auction']['id'], $auction['Auction']['end_time'], $data);
}
} else {
$bid = $this->Auction->Bid->lastBid($auction['Auction']['id']);
// lets set the autobid
if(!empty($bid) && ($bid['autobidder'] == 0)) {
$this->Auction->Autobid->check($auction['Auction']['id'], $auction['Auction']['end_time'], $data);
}
}
} elseif($auction['Auction']['extend_enabled'] == 1) {
unset($auction['Auction']['modified']);
$auction['Auction']['end_time'] = date('Y-m-d H:i:s', $endTime + ($auction['Auction']['time_extended']));
// lets do a quick check to make sure the new end time isn't less than the current time
$newEndTime = strtotime($auction['Auction']['end_time']);
if($newEndTime < time()) {
$auction['Auction']['end_time'] = date('Y-m-d H:i:s', time() + ($auction['Auction']['time_extended']));
}
$this->Auction->save($auction);
}
}
}
}
usleep(800000);
}
}
/**
* The function auto extends auctions in the last IF the extend function fails
*
* #return array Affected Auction
*/
function autobid() {
$data['bid_debit'] = $this->Setting->get('bid_debit');
$data['auction_time_increment'] = $this->Setting->get('auction_time_increment');
$data['auction_price_increment'] = $this->Setting->get('auction_price_increment');
$data['auction_peak_start'] = $this->Setting->get('auction_peak_start');
$data['auction_peak_end'] = $this->Setting->get('auction_peak_end');
$data['isPeakNow'] = $this->isPeakNow();
$isPeakNow = $this->isPeakNow();
$expireTime = time() + ($this->appConfigurations['cronTime'] * 60);
while (time() < $expireTime) {
// lets start by getting all the auctions that have closed
$auctions = $this->Auction->find('all', array('fields' => array('Auction.id', 'Auction.peak_only'), 'contain' => '', 'conditions' => "Auction.winner_id = 0 AND Auction.end_time <= '" . date('Y-m-d H:i:s', time() + 4) . "' AND Auction.closed = 0"));
if(!empty($auctions)) {
foreach($auctions as $auction) {
// before we declare this user the winner, lets run some test to make sure the auction can definitely close
if($this->Auction->checkCanClose($auction['Auction']['id'], $isPeakNow, false) == false) {
// lets check to see if the reason we can't close it, is because its now offpeak and this is a peak auction
if($auction['Auction']['peak_only'] == 1 && !$isPeakNow) {
continue;
} else {
$this->Auction->Autobid->placeAutobid($auction['Auction']['id'], $data);
}
}
}
}
usleep(900000);
}
}
/**
* The function closes the auctions
*
* #return array Affected Auction
*/
function close() {
$expireTime = time() + ($this->appConfigurations['cronTime'] * 60);
while (time() < $expireTime) {
// lets start by getting all the auctions that have closed
$auctions = $this->Auction->find('all', array('contain' => '', 'conditions' => "Auction.winner_id = 0 AND Auction.end_time <= '" . date('Y-m-d H:i:s') . "' AND Auction.closed = 0"));
if(!empty($auctions)) {
foreach($auctions as $auction) {
$isPeakNow = $this->isPeakNow();
// before we declare this user the winner, lets run some test to make sure the auction can definitely close
if($this->Auction->checkCanClose($auction['Auction']['id'], $isPeakNow) == false) {
// lets check to see if the reason we can't close it, is because its now offpeak and this is a peak auction
if($auction['Auction']['peak_only'] == 1 && !$isPeakNow) {
$peak = $this->nonPeakDates();
//Calculate how many seconds auction will end after peak end
$seconds_after_peak = strtotime($auction['Auction']['end_time']) - strtotime($peak['peak_end']);
$end_time = strtotime($peak['peak_start']) + $seconds_after_peak;
$auction['Auction']['end_time'] = date('Y-m-d H:i:s', $end_time);
$this->Auction->save($auction);
} else {
// lets check just how far ago this auction closed, and either place an autobid or extend the time
$data['auction_time_increment'] = $this->Setting->get('auction_time_increment');
$newEndTime = strtotime($auction['Auction']['end_time']);
if($newEndTime < time() - $data['auction_time_increment']) {
$auction['Auction']['end_time'] = date('Y-m-d H:i:s', time() + ($auction['Auction']['time_extended']));
$this->Auction->save($auction);
} else {
//lets extend it by placing an autobid
$data['bid_debit'] = $this->Setting->get('bid_debit');
$data['auction_price_increment'] = $this->Setting->get('auction_price_increment');
$data['auction_peak_start'] = $this->Setting->get('auction_peak_start');
$data['auction_peak_end'] = $this->Setting->get('auction_peak_end');
$data['isPeakNow'] = $this->isPeakNow();
$this->Auction->Autobid->placeAutobid($auction['Auction']['id'], $data);
}
}
continue;
}
$bid = $this->Auction->Bid->find('first', array('conditions' => array('Bid.auction_id' => $auction['Auction']['id']), 'order' => array('Bid.id' => 'desc')));
if(!empty($bid)) {
if($bid['User']['autobidder'] == 0) {
// send the email to the winner
$data['Auction'] = $auction['Auction'];
$data['Bid'] = $bid['Bid'];
$data['User'] = $bid['User'];
$data['to'] = $data['User']['email'];
$data['subject'] = sprintf(__('%s - You have won an auction', true), $this->appConfigurations['name']);
$data['template'] = 'auctions/won_auction';
$this->_sendEmail($data);
$auction['Auction']['status_id'] = 1;
}
$auction['Auction']['winner_id'] = $bid['Bid']['user_id'];
}
unset($auction['Auction']['modified']);
$auction['Auction']['closed'] = 1;
$this->Auction->save($auction);
}
}
usleep(900000);
}
}
}
?>
The CakePHP way to run crons is to build your own shells to do the tasks. Shells allows you full access to all of your controllers through the command prompt. Be sure to read this documentation when starting:
http://book.cakephp.org/view/108/The-CakePHP-Console
It shows you how to build your own shells (app/vendors/shells/), how to organize your shells into tasks, and how to properly run your shell as a cron job.
I do it a slightly different way than the documentation describes. My cron statement looks like:
* * * * * (cd /path/to/my/cake/app; sh ../cake/console/cake daily;) 1> /dev/null 2>&1
From there I simply have a shell called app/vendors/shells/daily.php
<?php
class DailyShell extends Shell {
var $uses = array('User');
function main() {
$this->User->processDailyTasks();
}
}
?>
This is far better and more stable than using curl in a cron job.

Resources