I am new to laravel4, I am working basically with SOAP webservices in laravel 4 using Nusoap library.
My problem is with pagination, at controller my code is ast follow
function AjaxProductList()
{
$isAjax = Request::ajax();
if($isAjax)
{
//instantiate the NuSOAP class and define the web service URL:
$client = new nusoap_client('http://stage.ws.greenbook.net/gbwswcf/servicegb.svc?wsdl', 'WSDL');
//check if there were any instantiation errors, and if so stop execution with an error message:
$error = $client->getError();
if ($error) {
die("client construction error: {$error}\n");
}
if(Input::get('term'))
{
Session::put('term', Input::get('term'));
$term = Input::get('term');
}
else
$term = Session::get('term');
if(Input::get('pg_number')!='')
{
Session::put('page_num', Input::get('pg_number'));
$page_num = Input::get('pg_number');
}
else
$page_num = Session::get('page_num');
if(Input::get('per_pg_result') !='')
{
Session::put('result_per_page', Input::get('per_pg_result'));
$result_per_page = Input::get('per_pg_result');
}
else
$result_per_page = Session::get('result_per_page');
$param = 'SearchParam=|category#'.Session::get('type').'|searchterm#'.$term;
//$value = Session::get('key');
$params = array( 'ClientID' => Config::get('globals.ClientID'),
'strPwd' => Config::get('globals.password'),
'Params' => $param ,
'PageNum' =>$page_num,
'NumOfResultsPerPage' =>$result_per_page
);
$client->soap_defencoding = 'UTF-8';
$answer = $client->call('GetResultsV2',$params);
//check if there were any call errors, and if so stop execution with some error messages:
$error = $client->getError();
if ($error) {
echo 'some error occured , please try again later';
die();
}
$ResultNumbers = Common::find_key_array('ResultNumbers',$answer);
$data['SearchParams'] = Common::find_key_array('SearchParams',$answer);
$data['products'] = Common::find_key_array('Product',$answer);
$data['total_result'] = $ResultNumbers['TotalNum'];
$data['paginator'] = **Paginator::make($data['products'],$data['total_result'],$result_per_page)**;
$return["prd_listing_bot"] = View::make('frontend.search.ajax_product_listing',$data)->render();
echo json_encode($return);
exit;
}
else
{
echo 'not allowed';
}
}
here i am using Paginatior class and providing the parameters (returned records,total items,perpage items).
here is my view code:
$paginator->setBaseUrl('search');
echo $paginator->links();
NOW its creating links successfully
My URL structure after clicking 5 is
'http://mydomain/search?page=5'.
and in 'routes.php' i have
Route::any('search', array('uses' => 'SearchController#QuickSearch'));
when the page view is loaded an ajax call is initiated for function AjaxProductList();
when i click on any link in pagination, it fatches data successfully, but not updating the active link. i.e if i click on page number 5 it will fetch the correct data but active link will be still at page "1".
tell me please if i am doing anything wrong?
thanks in advance.
Just solved it by placing
Paginator::setCurrentPage($page_num);
above the line
Paginator::make($data['products'],$data['total_result'],$result_per_page);
Anyway thanks to everyone who participated here.
In the Paginator::make() methos the first parameter is an array of items that are already paginated. Check this example:
$perPage = 15;
$currentPage = Input::get('page', 1) - 1;
$pagedData = array_slice($items, $currentPage * $perPage, $perPage);
$matches = Paginator::make($pagedData, count($items), $perPage);
In this example I use the array_slice methos to get the items of the current page. To get the page in your controller you can use Input::get('page', 1) so if there is no page selected to default would be 1
Related
So, I've developed the following code:
const MAILGUN_API_MAX_LIMIT = 300; //max in documentation
$mgClient = new Mailgun\Mailgun("<mailgun_key>");
$domain = "<my_domain>";
$resultItems = array();
try {
$result = null;
$endTime_Epoch = time();
$startTime_Epoch = $endTime_Epoch - 1440000; //400 hours
$queryParams = array(
'begin' => $endTime_Epoch,
'end' => $startTime_Epoch,
'limit' => MAILGUN_API_MAX_LIMIT,
'ascending' => 'no',
'event' => 'rejected OR failed',
);
$request_url = "$domain/events";
do {
$result = $mgClient->get($request_url, $queryParams);
if(!$result->http_response_body) {
/*...*/
} else if($result->http_response_code != 200) {
/*...*/
} else {
$resultItems[] = $result->http_response_body->items;
if(count($result->http_response_body->items) == MAILGUN_API_MAX_LIMIT) {
$request_url = $result->http_repsonse_body->paging->next;
}
}
} while($result && $result->http_response_body && count($result->http_response_body->items) == MAILGUN_API_MAX_LIMIT);
} catch (Exception $e) {
echo $e->getMessage()
}
But I'm having trouble getting it to page through the next set of requests if the limit ever gets hit (it probably won't, but it'd be bad in the event that something happened that made it happen).
I've tried reading mailgun's api doc, but i cannot, for the life of me, figure out what it is talking about with this:
require 'vendor/autoload.php';
use Mailgun\Mailgun;
# Instantiate the client.
$mgClient = new Mailgun('YOUR_API_KEY');
$domain = 'YOUR_DOMAIN_NAME';
$nextPage = 'W3siYSI6IGZhbHNlLC';
# Make the call to the client.
$result = $mgClient->get("$domain/events/$nextPage");
But i can't figure out what that $nextPage is supposed to be. I've tried peeling off the start of the paging->next so it just ends up being $domain/events/, but that doesn't seem to be paging though it. I'm not really sure what to do here, or even what I'm supposed to do.
I know this is a bit later than you would've hoped, but I've also been doing some stuff with the Mailgun and PHP lately.
So $nextPage is a value provided after your first API requests, so you don't need it at the start. Simply make your normal request like so
$result = $mailgun->get("$domain/events", $queryString);
// then we can get our 'Next Page' uri provided by the request
$nextURI = $result->http_response_body->paging->next;
// now we can use this to grab our next page of results
$secondPageResults = $mailgun->get($nextURI, $queryString);
Once thing worth noting though, is that Mailgun seems to always provide a 'next' link even when you've got all the results you want.
In my project I collected all results using a while loop after getting my initial records:
$hasNext = count($items) >= $queryLimit;
while($hasNext) {
$nextResult = $mailgun->get($lastResult->http_response_body->paging->next, $queryString);
$nextItems = $nextResult->http_response_body->items;
$items = array_merge($items, $nextItems);
$hasNext = count($nextItems) >= $queryLimit;
$lastResult = $nextResult;
}
Hope this helps!
I want to set all the advanced search parameter using session how to set all the parameter at time.
I am using following function but it only set one parameter at time how to set all the parameter at time
public function searchterm_handler($searchterm)
{
if($searchterm)
{
$this->session->set_userdata('searchterm', $searchterm);
return $searchterm;
}
elseif($this->session->userdata('searchterm'))
{
$searchterm = $this->session->userdata('searchterm');
return $searchterm;
}
else
{
$searchterm ="";
return $searchterm;
} }
Method one (recommended)
So for pagination in CodeIgniter, you have 3 main variables you must set and a configuration method to call. You also have a library you must load.
The library is $this->load->library('pagination');
The 3 variables and configuration look like this:
//This next line is used mainly so the page number links on your pagination work.
$config['base_url'] = 'http://example.com/index.php/test/page/';
$config['total_rows'] = $NumberOfRecords;
$config['per_page'] = 20;
$this->pagination->initialize($config);
If you are using MVC then this is quite simple. You would use the above code in your controller, grab the data you want to display starting at the nth row, where n is the page number * $config['per_page'], and ending at ((page number * $config['per_page']) + $config['per_page'])-1.
After getting the necessary data you would return that and the link code to your view. The link code is $this->pagination->create_links();
So your return might look something like this:
$data["results"] = $this->MyModel->MySqlMethod($config["per_page"], $CurrentPage);
$data["links"] = $this->pagination->create_links();
Then in your view you would loop through the $data["results"] and after the loop you would display the $data["links"]
This would give you your data displayed then the pagination at the bottom would look something like
So your controller all together should look like:
$config['base_url'] = 'http://example.com/index.php/controllerName/ViewName/';
$config['total_rows'] = $NumberOfRecords;
$config['per_page'] = 20;
$this->pagination->initialize($config);
$data["results"] = $this->MyModel->MySqlMethod($config["per_page"], $CurrentPage);
$data["links"] = $this->pagination->create_links();
return $this->load->view("ViewName", $data);
Method Two (NOT recommended)
Now you mentioned something about storing that data in Session Variables. I mean if you want you can do this. If you are going to use that method, then that tell you are not using MVC. CodeIgniter is meant for MVC. If you are not using MVC then you probably do not need CodeIgniter. If you are comfortable using CodeIgniter and do not want to try and implement the MVC, by all means go ahead.
To do the CodeIgniter Pagination in this method, you would change your public searchterm_handler($searchterm) function. The thing with session variables is that they are stored on the users browser so that way you, the programmer, can access them anywhere on your site without having to return and pass them from class to class or method to method. If you set a session variable then you return it, that is redundent and unnecessary.
You don't really need this method, it is unnecessary, but you could do something like this:
public function searchterm_handler($searchterm) {
$result = mysqli_query("SELECT count(*) FROM User_info");
$row = mysqli_fetch_row($result);
$TotalDataCount = $row[0];
$this->session->set_userdata("TotalDataCount", $TotalDataCount);
$this->session->set_userdata("RecordsPerPage", 20);
$this->session->set_userdata("BaseURL", www.example.com/link/to/your/page.php);
$this->pagination->initialize($config);
if($searchterm) {
$this->session->set_userdata('searchterm', $searchterm);
//Unnecessary
//return $searchterm;
} else {
$this->session->set_userdata('searchterm', "");
//return $searchterm;
}
}
Then in the code that called searchterm_handler($searchterm), you would do this:
searchterm_handler($input);
$searchterm = $this->session->userdata('searchterm');
$dataToReturn = array();
if($searchterm!="") {
$result = mysqli_query("SELECT * FROM table WHERE field LIKE '%$this->session->userdata('searchterm')%'");
if($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
echo $this->pagination->create_links();
LET ME WORN YOU
This second method, is gross and ugly and yucky and very badly written. There is no real good way to write what you want to write. The purpose of using CodeIgniter is for MVC and built in CodeIgniter functionality, which you lose almost all of it when you get rid of MVC.
I know there is a chance I misunderstood what you are trying to do, but this was my best guess. My best advice for you is to use MVC in CodeIgniter.
Here are some sources that may help you if you use the first method:
https://www.sitepoint.com/pagination-with-codeigniter/
https://www.codeigniter.com/userguide3/libraries/pagination.html
I hope this helps, I spent a lot of time writing it...
Update - Method 3
I tried looking at your question again and maybe this will help
public function searchterm_handler($searchterm)
{
if($searchterm && $this->session->userdata('email'))
{ //user logged in
$this->session->set_userdata('searchterm', $searchterm);
$array = array(
"searchterm" => $searchterm,
"email" => $this->session->userdata('email'),
"username" => $this->session->userdata('username')
);
return $array;
}
else if($searchterm && !$this->session->userdata('searchterm'))
{ //user not logged in
$this->session->set_userdata('searchterm', $searchterm);
return $searchterm;
}
elseif($this->session->userdata('searchterm') && $this->session->userdata('searchterm'))
{ //user logged in
$searchterm = $this->session->userdata('searchterm');
$array = array(
"searchterm" => $searchterm,
"email" => $this->session->userdata('email'),
"username" => $this->session->userdata('username')
);
return $array;
}
elseif($this->session->userdata('searchterm') && !$this->session->userdata('searchterm'))
{ //user not logged in
$searchterm = $this->session->userdata('searchterm');
return $searchterm;
}
else
{
$searchterm ="";
return $searchterm;
} }
sorry if this is may, I did it on my phone
Since I have several functions executing in the following control as a single transaction I couldn't surround each function as a transaction in the model. So I did it the following way. Please someone let me know if there is any problem. Works fine for now, but have no idea whether it will get any concurrency issues or there is any other way?
if(isset($_POST['btnsave']))
{
$mcodes = $_POST['tblmcode'];
$count = count($mcodes);
//echo $count;
$issue = new Materialissue_model();
$this->db->trans_start(); //Here starts my transaction
$issue->setIssuecode($this->input->post('txtissuecode'));
if($issue->checkNoExistence()) {
$issue->setDate($this->input->post('txtdate'));
$issue->setCustomer($this->input->post('txtcustomer'));
$issue->setFromlocation($this->input->post('txtlocation'));
$issue->setResponsible($this->input->post('txtresponsible'));
$issue->setComments($this->input->post('txtcomments'));
$issue->setTotal($this->input->post('txttotal'));
$issue->setUser($this->session->userdata('username'));
$issue->setStatus($this->input->post('txtstatus'));
for ($i = 0; $i < $count; $i++) {
$issue->setMaterialcode($_POST['tblmcode'][$i]);
$issue->setMaterialname($_POST['tblmname'][$i]);
$issue->setCost($_POST['tblcost'][$i]);
$issue->setQty($_POST['tblqty'][$i]);
$issue->setSubtotal($_POST['tblsubtotal'][$i]);
$issue->saveIssueDetail();
$stock = new Materialstock_model();
$stock->setItemcode($_POST['tblmcode'][$i]);
$stock->setItemlocation($this->input->post('txtlocation'));
$stock->setQty($_POST['tblqty'][$i]);
$stock->setRefno($this->input->post('txtissuecode'));
$stock->setLasttransaction('MATERIAL-ISSUE');
$stock->updateMaterialIssueStock();
$transaction = new Transaction_model();
$transaction->setDescription("MATERIAL-ISSUE");
$transaction->setItemcode($_POST['tblmcode'][$i]);
$transaction->setRecqty("0");
$transaction->setTransqty("0");
$transaction->setIssueqty($_POST['tblqty'][$i]);
$transaction->setDate($this->input->post('txtdate'));
$transaction->setUser($this->session->userdata('username'));
$transaction->saveMaterialTransaction();
}
$result = $issue->saveIssue();
$this->db->trans_complete(); //Here ends my transaction
if ($result) {
$message = new Message_model();
$data['message'] = $message->recordadded;
$data['type'] = "success";
$data['returnpage'] = base_url() . "index.php/materialissue_control/show";
$data["print"] = base_url() . "index.php/Notegenerator_control/showMaterialIssueNote?code=".$issue->getIssuecode();
$this->load->view('messageprint_view', $data);
}
}else{
$message = new Message_model();
$data['message'] = $message->issuecodeexists;
$data['type'] = "error";
$data['returnpage'] = base_url() . "index.php/materialissue_control/show";
$this->load->view('message_view', $data);
}
}
I prefer like using trigger to handle many functions in one controller, this make mycode clean and easy to track. example:
user writes article, this action will call one action in model write_article combine with 1 transaction, but this function run any query :
1.insert post
2.lock count post category
3.lock count user post
4.lock count post by date
example in code
public function write_article($post) {
$this->cms->db->trans_start(TRUE);
$this->cms->db->set('content', $posts->get_content());
$this->cms->db->insert('t_posts');
$this->cms->db->trans_complete();
if($this->cms->db->trans_status() === TRUE){
$this->cms->db->trans_commit();
}else{
$this->cms->db->trans_rollback();
}
}
This reference about trigger
www.sitepoint.com/how-to-create-mysql-triggers
Request yo to help in pagination links .
In my database i have 3 records i want to display single record per page. When I select the next numeric of pagination link, data is not being fetched.Thing is that when I click on number 2 of pagination link, echo var_dump() shows Result is empty and I am not getting any values for echo $data->email.But for the first time when i search i am able to display single record, problem is only with next link of pagination So what might be the error? I'm not able to get an answer,and I'm not sure what happens, so I am posting my code below please go through it and and help me.
Request you to help me.
**HERE STARTS MY CONTROLLER**
public function users($limit=1,$offset = 0)
{
$this->load->helper('url');
$data = array();
$look = $this->input->post('look');
$age = $this->input->post('age');
$age_from = $this->input->post('age_from');
$age_to = $this->input->post('age_to');
$se_ct = $this->input->post('sect');
$subsect = $this->input->post('subsect');
$coun_try = $this->input->post('country');
$sta_te = $this->input->post('state');
$ci_ty = $this->input->post('city');
$qualification = $this->input->post('qualification');
$results = $this->searchresultss->login($look, $age, $age_to, $age_from, $se_ct, $subsect, $coun_try, $sta_te, $ci_ty, $qualification);
$this->load->helper('url');
$config = array();
$config['base_url'] = base_url().'searchresult/users';
$config['total_rows'] = count($results);
$config['per_page'] = $limit;
$this->load->library('pagination', $config);
$data['pagination_links'] = $this->pagination->create_links();
$data['results'] = array_slice($results, $offset, $limit);
$this->load->view('searchresult', $data);
$this->load->view('includes/khelp');
$this->load->view('includes/kfooter');
**HERE STARTS MY MODEL PAGE**
Class Searchresultss extends CI_Model
{
public function login($look, $age, $age_to, $age_from, $se_ct, $subsect, $coun_try, $sta_te, $ci_ty, $qualification)
{
return $this->db->query("SELECT *
FROM users
WHERE gender = '$look'
And status='1'")->result();
}
}
**HERE START MY VIEW PAGE**
echo var_dump($_POST);
if (empty($results)) {
echo 'Results set is empty';
} else
{
foreach ($results as $data) {
echo $data->email.'<br />';
}
}
echo $pagination_links;
The problem lies in the fact that the pagination links do not include the POST variables (as well as the fact that hyper links are requested via GET).
I recommend you do a var_dump() on $_GET and $_POST and the problem will become more obvious.
A possible solution would be to include the post variables as url parameters. So for example
$config['base_url'] = base_url().'searchresult/users/look_param/age_param/etcetc';
However you would need to add functionality to handle the above.
I'm about to pull my hair over this!
On initial load of my page with pagination (by CI), all rows are displayed, even if I only want 3. On click of other pages, however, it works fine (the correct rows are displayed), but Page 1 is always "selected" (not clickable), even if I click on Page 2, 3, etc.
Any ideas?
My CONTROLLER:
function album($type, $album_id, $album_name) {
$this->load->library('pagination');
$config['base_url'] = base_url("photo_store/album/$type/$album_id/$album_name/");
$config['total_rows'] = $this->Media_model->get_photos($album_id, 'display_date DESC', NULL, NULL, TRUE);
$config['per_page'] = 3;
$this->pagination->initialize($config);
$album_photos = $this->Media_model->get_photos($album_id, 'display_date DESC', $config['per_page'], $this->uri->segment(6), FALSE);
$this->_load_view(array(
/* some other variables here */
'album_photos' => $album_photos
));
)
private function _load_view($more_data) {
$data = array_merge($more_data, array( /* some other variables here */ ));
$this->load->view('template', $data);
}
My MODEL:
public function get_photos($album_id=NULL, $order_by='display_date DESC', $limit=NULL, $offset=NULL, $count=FALSE) {
$result = array();
$query = $this->db->select('medium.*')->join('medium', "$this->item.medium_id = medium.id", 'inner')->order_by($order_by);
$limit = $limit ? $limit : '0';
$offset = $offset ? $offset : '0';
if ($limit!=='0' && $offset!=='0') {
$query->limit($limit, $offset);
}
if ($album_id) { $result = $query->get_where($this->item, array('album_id' => $album_id)); }
else { $result = $query->get($this->item); }
if ($count){ return $result->num_rows(); }
else { return $result->result(); }
}
My VIEW:
foreach ($album_photos as $photo) {
//display photos here
}
echo $this->pagination->create_links();
You can just add this to the config array so the pagination knows where to find the current page:
$config['uri_segment'] = 4;
I believe part of the problem is coming in here:
if ($limit!=='0' && $offset!=='0') {
$query->limit($limit, $offset);
}
Since you don't have an else part for your statement, the query is never limited for that first page.
I suggest you change that code to
if ($limit!=='0') {
$query->limit($limit, $offset);
}
or even just
$query->limit($limit, $offset);
since $limit should theoretically never be null or 0 because you've set it to 3. $offset, unless set, should be 0 so you could replace null with it in your model's function,
When there are more than 3 uri segments passed in the url, selected page of pagination will not be displayed correctly, it will highlight the first page all the time.
Pagination is working, but the selected page is not diplayed correctly.
To solve this, solution:
go to Pagination.php file which is located at system->libraries->Pagination.php
just simply set
var $uri_segment = 4;// or 5 or 6;
It will work.
You can just add this to the config array so the pagination knows where to find the current page:
$config['uri_segment'] = 4; // Your appropriate uri segment: 5 or 6
Try to code your controller like below:
public function index($page=''){
//...
$page = ($page!='')? $page : 0;
$config["cur_page"] = $page;
//...
}