CakePHP 3.0 Modelless Pagination - cakephp-3.0

I have data coming from an API that I want to show results for using CakePHP's pagination. Everything I see for the pagination requires a query or model object to be passed in. Is it possible to pass in something like an array of the data or total items, current item, and items per page?

The solution was easier than I anticipated. I was able to add a paging element to the request params. The pagination component doesn't need to be touched at all.
$data = $Utility->getData();
$perPage = 20;
$count = count($data);
$page = isset($this->request->query['page']) ? $this->request->query['page'] : 1;
$offset = $perPage * ($page - 1);
$pageCount = floor($count / $perPage);
$this->request->params['paging'] = [
'Messages' => [
'page' => $page,
'current' => $offset,
'count' => $count,
'perPage' => $perPage,
'prevPage' => $page != 1,
'nextPage' => $page != $pageCount,
'pageCount' => $pageCount,
]
];

Related

Api Response and Json laravel format

I'm using Laravel 5.7. and GuzzleHttp 6.0 to get API response
from endpoint
I'm passing query data from Blade form to this function.
public static function prhmulti($multisearch, $start ,$end)
{ $city = $multisearch['city'];
$client = new Client([
'base_uri' => 'https://avoindata.prh.fi/tr/',
'query' => [
'totalResults' => 'true',
'maxResults' => '1000',
'registeredOffice'=> $city,
'companyForm'=>'OY',
'companyRegistrationFrom'=>$start,
'companyRegistrationTo'=>$end,
],
'defaults'=>[
'timeout' => 2.0,
'cookies' => true,
'headers' => [
'content-type' => 'application/json',
'User-Agent' =>"GuzzleHttp/Laravel-App-5.7, Copyright MikroMike"
]]]);
$res = $client->request('GET','v1');
$ResData = json_decode($res->getBody()->getContents());
dd ($ResData) gives all data from API response.
But I am not able to return JSON back to other function
return $this->multisave($ResData);
public static function multisave (data $ResData)
This will parse JSON and
{
foreach ($data->results as $company) {
$name = $company->name;
$Addr = $company->addresses;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
foreach ($company->addresses as $Addr) {
$city = $Addr->city;
$postcode = $Addr->postCode;
$street = $Addr->street;
}
}
save data to Mysql.
$NewCompany = new Company();
$NewCompany = Company::updateOrCreate($array,[
[ 'vat_id', $businessId],
[ 'name', $name],
[ 'form',$companyForm],
[ 'street', $Addr],
[ 'postcode', $postcode],
[ 'city', $city],
[ 'regdate', $registrationDate],
]);
}
IF Parse part and Save part is inside same function code works ok(save only one company),
but I need to separate them because later on it's easier to maintain.
Error which I am getting to return $ResData
" Using $this when not in object context"
Information is in JSON array.
Also foreach part save ONLY one company ?
foreach ($data->results as $company) {
$name = $company->name;
$Addr = $company->addresses;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
foreach ($company->addresses as $Addr) {
$city = $Addr->city;
$postcode = $Addr->postCode;
$street = $Addr->street;
}
So : 1) What is best way to create own function for parse JSON
and other for save data to DB?
2) As foreach loop save only one company data, What is
best way to fix it?
Thanks MikroMike.
Resolved my own question for saving companies to db
First get total number inside Array
use for-loop to make counting
use foreach-loop extract information per single company as object.
$data = json_decode($res->getBody()->getContents());
$total = $data->totalResults;
for ($i = 0; $i < $total; $i++){
$NewCompany = new Company();
foreach ($data->results as $company)
{
$name = $company->name;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
$array = [];
Arr::set($array, 'vat_id', $businessId);
Arr::set($array, 'name', $name );
Arr::set($array, 'form', $companyForm);
Arr::set($array, 'regdate', $registrationDate);
$NewCompany = Company::updateOrCreate($array,[
[ 'vat_id', $businessId],
[ 'name', $name],
[ 'form',$companyForm],
[ 'regdate', $registrationDate],
]);
}// END OF MAIN FOREACH
}// END OF For loop
}// END OF FUCNTION
} // END OF CLASS

How to get the JSON data from the Groupon API

I am struggling to get the "merchant" -> "id" from the Groupon API below, while I don't have any problems to return the discountPercent.
<?php
$url = 'https://partner-int-api.groupon.com/deals.json?country_code=IE&tsToken=IE_AFF_0_200012_212556_0&division_id=dublin&offset=0&limit=10';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['deals'] as $results) {
$discountPercent = $results['options'][0]['discountPercent'];
$merchantId = $results['merchant'][0]->id;
echo $discountPercent.'<br>';
echo $merchantId;
}
?>
If someone could point me to the right direction.
Many Thanks,
Ok here is the answer:
$merchantId = $results['merchant']['id'];
>>>This may be the Reason.....
>>>Explanation for:: $results['options'][0]['discountPercent']
In $json array you can see
[options] => Array
(
[0] => Array
(
.........
[discountPercent] => 54
.........
)
)
Here, the hierechy is
option->0(key)->discountPercent
that's why you need to use index '0';
>>>Explanation for::: $results['merchant'][0]->id
in json array you can see
[merchant] => Array
(
[id] => global-cuisine-restaurant
[uuid] => 183dd76b-a1a6-40cf-93c7-33e00f379451
[name] => Global Cuisine Restaurant
[websiteUrl] => http://www.globalcuisine.ie/
[twitterUrl] =>
[facebookUrl] =>
[ratings] =>
)
Here the hirerchy is:::
merchant->id (notice '0' is not present as any subarray index)
that's why should use
$merchantId = $results['merchant']['id'];
finally use can use code::
<?php
$url = 'https://partner-int-api.groupon.com/deals.json?country_code=IE&tsToken=IE_AFF_0_200012_212556_0&division_id=dublin&offset=0&limit=10';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['deals'] as $key=>$results) {
$discountPercent = $results['options'][0]['discountPercent'];
$discountPercent[] = $results['options'][0]['discountPercent'];//to get all in one;
$merchantId = $results['merchant']['id'];
$merchantId[] = $results['merchant']['id'];//to get all in one
echo $discountPercent.'<br>';
echo $merchantId;
}
?>

API Json in symfony form

i'm creating an application in symfony 2.8 (with php5.4) and in my form (that i'm building) i want to display a list of a projects through an API in json format.
Now i'm stuck, and i don't know how to do this.
I know the database of the API there is a table "projects" and i want target the column 'name' to display names of projects
here's my code:
/**
* #Route("/form")
*/
public function formAction(Request $request)
{
$url = 'https://website.com/projects.json';
$get_json = file_get_contents($url);
$json = json_decode($get_json);
$form = $this->createFormBuilder()
->add('Project', 'choice') // <-- ???
->add('send', 'submit' ,array('label' => 'Envoyer'))
->getForm();
$form->handleRequest($request);
return $this->render('StatBundle:Default:form.html.twig', array('form' => $form->createView(), 'project' => $json));
}
You can pass the choice as second argument as array as example:
$jsonAsArray = json_decode($get_json, true); // with true return an array
$builder->add('Project', 'choice', array(
'choices' => $jsonAsArray,
// *this line is important, depends of the data*
'choices_as_values' => false,
));
More info in the doc here.
Hope this help

Codeigniter - insert batch - multiple inputs with same name

I am trying to insert a batch of rows for wholesale, dealer and customer
Note : i am using 'append' to add row of inputs but then they carry the same input names.
I am trying to apply this to wholesale first but it is not happening
when i add another row to my wholesale input list it is taking only one row(my last row) input and my other row of inputs are discarded. the var_dump of array reveals that.
This is my controller file
$range = $this->input->post('wrange1');
$usertype = $this->input->post('wusertype');
$uom = $this->input->post('wuom1');
$price = $this->input->post('wamount1'); //array of price
$vat = $this->input->post('wvat1');
var_dump($range);// i am getting only one output
$updateArray = [];
for($x = 0; $x < sizeof($price); $x++){
$updateArray[$x] = array(
'product_id'=> $id,
'range' => $range[$x],
'usertype' => $usertype[$x],
'uom' => $uom[$x],
'price' => $price[$x],
'vat' => $vat[$x]
);
}
$this->productmodel->updatepricinglist($updateArray);
This is my model file:
public function updatepricinglist($updateArray) {
$this->db->insert_batch('product_pricing', $updateArray);
}
use insert operation inside for loop.and if you get the array in all the field then you have to use array of index like in for loop , since you said you get only one range at output then don't use array of index in loop.
$range = $this->input->post('wrange1');
$usertype = $this->input->post('wusertype');
$uom = $this->input->post('wuom1');
$price = $this->input->post('wamount1'); //array of price
$vat = $this->input->post('wvat1');
var_dump($range);// i am getting only one output
for($x = 0; $x < sizeof($price); $x++){
$updateArray = array(
'product_id'=> $id,
'range' => $range,
'usertype' => $usertype[$x],
'uom' => $uom[$x],
'price' => $price[$x],
'vat' => $vat[$x]
);
$this->productmodel->updatepricinglist($updateArray);
}

Add items to query result - Laravel

I'm slowly moving my API to Laravel and coming to grips with the Query Builder.
I'm trying to achieve this:
$data = array();
$query = "SELECT * FROM blog_posts WHERE post_type = 3 AND post_status = 1 ORDER BY id DESC";
$result = mysqli_query($cms_connection, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
$row['post_seo'] = seoUrl($row['post_title']);
$data['data'][] = $row;
}
$data['success'] = true;
$response = json_encode($data);
}
My problem isn't necessarily with getting the query, but as you can see I'm using the result of the query and then injecting it back into the final array.
So essentially, I'm fetching rows, transforming some of the attributes fetched, and then injecting the newly created attributes into the resulting array.
This is what I have so far:
$posts = DB::table('blog_posts')
-where(['post_type' => 1, 'post_status' => 1)
->orderBy('id', 'desc')
->take(5)->get();
You could do it this way
// get your data (yours part of code)
$posts = DB::table('blog_posts')
-where(['post_type' => 1, 'post_status' => 1])
->orderBy('id', 'desc')
->take(5)->get();
// add post_seo
foreach ($posts as $post) {
$post->post_seo = seoUrl($post->post_title);
}
// set result array
$data['data'] = $posts;
$data['success'] = true;
// response
$response = response()->json($data);
// or in case you want to return it just
return response()->json($data);
EDIT
You could do it also a bit better, using Eloquent. If you have such model (you need to add valid namespaces and use statements)
class BlogModel extends Model
{
protected $table = 'blog_posts';
protected $appends = ['post_seo'];
public function getPostSeoAttribute($value)
{
return seoUrl($this->post_title);
}
}
(added accessor to post_seo attribute and added post_seo to results when converting to array)
You can now do (shorter syntax than in previous example):
// get your data
$posts = BlogPost::where('post_type',1)
->where('post_status',1)
->orderBy('id', 'desc')
->take(5)->get();
// response
$response = response()->json(['data' => $posts, 'success' => true]);