Rendering view for DOMPDF in phalconPHP - angularjs

I have been try to convert template to PDF with DOMPDF in phalconPHP with angularJS at the front. But I am getting 500 internal server error response from it. DOMPDF is included fine in the controller as I loaded static HTML in load_html() function, it worked fine. Below is the report action from ReportsController. Don't bother with the whole code and just skip to the DOMPDF related code at the end. And $patients is the array that contains all the data which the template is going to need.
ReportController's reportAction:
public function reportAction()
{
$patientsModel = new Patients();
$patients = array();
$patients['data'] = array();
$tmpfilters = $this->queryfilters;
unset($tmpfilters['limit']);
$tmpfilters2 = array();
$tmpfilters2['models'] = "PRM\\Models\\Patients";
if( isset( $tmpfilters['conditions'] ) )
{
$tmpCondition = preg_replace("/[^0-9]/", '', $tmpfilters['conditions']);
$tmpfilters2['conditions'] = "clinic = " . $tmpCondition . " AND status = 24";
}
else
{
$tmpfilters2['conditions'] = "status = 24";
}
$tmpActivePatients = new Patients();
$tmpActivePatients = $tmpActivePatients->find($tmpfilters2);
$patients['activeTotal'] = $tmpActivePatients->count();
$tmpfilters3 = array();
$tmpfilters3['models']['m'] = "PRM\\Models\\Activity";
$tmpfilters3['models']['s'] = "PRM\\Models\\Patients";
if( isset( $tmpfilters['conditions'] ) )
{
$tmpCondition2 = preg_replace("/[^0-9]/", '', $tmpfilters['conditions']);
$tmpfilters3['conditions'] = "m.clinic = " . $tmpCondition2 . " AND " . "s.clinic = " . $tmpCondition2 . " AND m.patient=s.id AND m.duration > 1";
}
else
{
$tmpfilters3['conditions'] = "m.patient = s.id AND m.duration > 1";
}
$tmpPatientDuration = new Query($tmpfilters3);
$tmpPatientDuration = $tmpPatientDuration->getQuery()->execute();
//$builder = $this->modelsManager->createBuilder();
$patients['billableTotal'] = $tmpPatientDuration->count();
//$builder->addFrom('PRM\\Models\\Activity', 'a')->innerJoin('PRM\\Models\\Patients', 'p.id=a.patient', 'p')->where('a.duration > 1 AND p.status = 24');
//$result = $builder->getQuery()->execute();
//$patients['billableTotal'] = $result->count();
foreach ($tmpPatientDuration as $patient) {
array_push($patients['data'], array(
'id' => $patient->id,
'firstname' => $patient->s->firstname,
'lastname' => $patient->s->lastname,
'duration' => $patient->m->duration,
'billingCode' => "CPT 99490"));
/*'icd1' => Ccm::findFirstById($patient->icd1)->icdcode,
//'icd2' => Ccm::findFirstById($patient->icd2)->icdcode,
//'clinic' => Clinics::findFirstById($patient->clinic)->name,
'duration' => Activity::sum([
"column" => "duration",
"conditions" => "patient = '{$patient->id}'",
]),
'response' => Activity::findFirst([
"conditions" => "patient = '{$patient->id}' and activity='Communication' ",
"order" => "id desc"
])->description,
'status' => Status::findFirstById($patient->status)->name));*/
}
$html = $this->view->getRender("reports", "report", $patients);
$dompdf = new domPdf();
$dompdf->load_html($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
//$this->response->setJsonContent($patients);
$this->response->setContentType('application/pdf');
$this->response->setContent($dompdf->stream());
$this->response->send();
}
Here is the angularJS controller's code:
$http.get('common/reports/report', {responseType: 'arraybuffer'}).success(
function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}).error(
function (data) {
angular.forEach(data, function (error) {
$scope.error[error.field] = error.message;
console.log(error.field);
});
$alert({title: 'Error!', content: data.flash.message, placement: 'top-right', type: data.flash.class , duration: 10, container: '.site-alert'});
}
);
error logs:
error log for the above problem

Related

Notice (8): Undefined index: From when fetching message response from Google API-PHP Client

I am trying to list user messages in GMail Inbox.
$client = $this->getClient();
$service = new \Google_Service_Gmail($client);
$opt_param = array('labelIds' => 'INBOX');
$messagesResponse = $service->users_messages->listUsersMessages($user, $opt_param);
for ($i = 0; $i < $total; $i++) {
$messageToGet = ($messagesResponse->messages[$i]->id);
$message = $service->users_messages->get($user, $messageId);
$names = array_column($message->payload->headers, 'name');
$values = array_column($message->payload->headers, 'value');
$mail = array_combine($names, $values);
$senderMail = explode("<", $mail['From']);
if (count($senderMail) == 1) {
if (strpos($senderMail[0], '#') !== false) {
$senderName = [];
$domain[0] = substr($senderMail[0], strpos($senderMail[0], "#") + 1);
} else {
Log::info('Sender email could not be found');
return;
}
} else {
$senderName = [];
if ($senderMail[0] != "") {
$senderName = $senderMail[0];
$senderName = explode(" ", $senderName);
}
$senderMail = explode(">", $senderMail[1]);
$domain = explode("#", $mail['From']);
$domain = explode(">", $domain[1]);
}
...
}
When I tried to fetch 'From' from this $message response, it is throwing an undefined index error while fetching response for a message.
Notice: Notice (8): Undefined index: From in [File]
When I tried to debug the messages response return by the google api-php client, it resulted as below for all the messages
[16] => Google\Service\Gmail\MessagePartHeader Object
(
[name] => From
[value] => "Firstname Lastname" <firstname.lastname#gmail.com>
[internal_gapi_mappings:protected] => Array
(
)
[modelData:protected] => Array
(
)
[processed:protected] => Array
(
)
)
For one message, it returned
[16] => Google\Service\Gmail\MessagePartHeader Object
(
[name] => FROM
[value] => noreply#<domain>.org
[internal_gapi_mappings:protected] => Array
(
)
[modelData:protected] => Array
(
)
[processed:protected] => Array
(
)
)
Can anyone kindly let me know why the value of [name] key differs from From to FROM? Are there any more formats for the [name] key?
Thanks in Advance.

How to pass multi-dimensional arrays through url as query parameters? and access these parameters in laravel 6.0

I am trying to pass a multi-dimensional array as a query parameter in the below URL:
{{serverURL}}/api/v1/classes?with[]=section.courseteacher&addl_slug_params[0][0]=test&addl_slug_params[0][1]=test1&addl_slug_params[0][2]=test0
what is wrong with the above URL?
My code to access these parameters in Laravel 6.0 is below:
$addl_slug_params = $request->query('addl_slug_params');
$i=0;
foreach ($addl_slug_params as $s) {
$j=0;
foreach($s as $asp) {
print_r('addl_slug_params : ('.$i.':'.$j.') : '.$asp); die();
$j=$j+1;
}
$i = $i+1;
}
Result:
addl_slug_params : (0:0) : test
Problem: test1 and test0 are not accessible..
What should I do?
The problem is the die(); after printr(), the loop will run once, aka only addl_slug_params : (0:0) : test
To help you visualize it better, I added an extra break after each loop:
foreach ($addl_slug_params as $s) {
$j=0;
foreach($s as $asp) {
echo('addl_slug_params : ('.$i.':'.$j.') : '.$asp);
echo nl2br(PHP_EOL);
$j=$j+1;
}
$i = $i+1;
}
Will result in the following:
addl_slug_params : (0:0) : test
addl_slug_params : (0:1) : test1
addl_slug_params : (0:2) : test0
here is a solution for multi-dimensional arrays. Developed in 2~ hours, definitely needs improvement but hopefully helps you out :)
Route::get('example', function (\Illuminate\Http\Request $request) {
$addl_slug_params = [
[
1 => [
'title' => 'Test 1',
'slug' => 'test1'
],
2 => [
'title' => 'Test 2',
'slug' => 'test2'
],
3 => [
'title' => 'Test 3',
'slug' => 'test3'
],
],
];
// Encode
$prepend = 'addl_slug_params';
$query = "?$prepend";
$tempSlugs = $addl_slug_params[0];
$lastIndex = count($tempSlugs);
foreach ($addl_slug_params as $pIndex => $params) {
foreach ($params as $sIndex => $slugData) {
$tempQuery = [];
foreach ($slugData as $sdIndex => $data) {
// Replace '-' or ' -' with ''
$encodedString = preg_replace('#[ -]+#', '-', $data);
// title = test1
$tempString = "$sdIndex=$encodedString";
$tempQuery[] = $tempString;
}
$dataQuery = implode(',', $tempQuery);
$appendStr = ($sIndex !== $lastIndex) ? "&$prepend" : '';
// Set the multidimensional structure here
$query .= "[$pIndex][$sIndex]=[$dataQuery]$appendStr";
}
}
// DECODE
// ?addl_slug_params[0][1]=[title=Test-1,slug=test1]&addl_slug_params[0][2]=[title=Test-2,slug=test2]&addl_slug_params[0][3]=[title=Test-3,slug=test3]
$slugParams = $request->query('addl_slug_params');
$slugParamData = [];
foreach ($slugParams as $slugItems) {
foreach ($slugItems as $slugItem) {
// Replace [title=test,slug=test1] into 'title=test,slug=test1' and explode
// into into an array, and split title=test into [title => test]
$splitArray = explode(',', (str_replace(array('[', ']'), '', $slugItem)));
$slugItemData = [];
foreach ($splitArray as $value) {
$data = explode('=', $value);
$slugItemData[$data[0]] = $data[1];
}
$slugParamData[] = $slugItemData;
}
}
dd($slugParamData);
});
I have solved the problem using associative arrays as it gives more flexibility and Garrett's solution definitely helped
new url: {{serverURL}}/api/v1/classes?with[]=section.courseteacher&addl[users][params]=name
laravel code:
`
foreach ($addl_data_array as $addl_slug => $addl_slug_data) {
foreach ($addl_slug_data as $key => $value) {
$params = null;
$where_raw = null;
$where_has = null;
$with_relationships = null;
$with_timestamps = null;
}
}
`

Display Progress message after calling api url

we select checbox & onclick button "Show Status" , I am calling external webservice api url & updating the "status" column [4th in below image] values in Database.....
once we got success response we are displaying alert message....
Requirement :
but now i want to display Progress like "1% completed , 2 % completed" , so on.... :
status page
<button type= "button" id="show_status" >Show Status</button>
script
$('#show_status').click(function()
{
var selected = [];
$('.assigneeid-order:checked').each(function()
{
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var jsonString = JSON.stringify(selected);
$.ajax
({
type: "POST",
url: "api.php",
data: {data : jsonString},
success: function(response)
{
response = $.parseJSON(response);
alert("completed");
$.each(response, function(index, val)
{
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
}
});
});
api.php
<?php
$data = json_decode(stripslashes($_POST['data']));
$response = array();
foreach($data as $id){
$post_data['username']='a';
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
//print_r($orderResults); die;
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
echo json_encode($response);
?>
Please try this script and code
$('#show_status').click(function()
{
var selected = [];
$('.assigneeid-order:checked').each(function(){
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var count = selected.length
var perPlush = 100/count;
var per = 0;
for (var i = 0; i <= count; i++) {
$.ajax
({
type: "POST",
url: "api.php",
data: {id : selected[i]},
success: function(response)
{
response = $.parseJSON(response);
$.each(response, function(index, val)
{
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
per = per + perPlush;
console.log(Math.round(per) + " % Complated");
$("#progress").html(Math.round(per) + " % Complated");
}
});
}
});
Your api.php file
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX);
require_once("dbcontroller.php");
$db_handle = new DBController();
$id = $_POST['id']; //960856092
$response = array();
$orderid = $id;
$hide = '';
$post_data['awb']=$orderid;
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, "http://plapi.ecomexpress.in/track_me/api/mawbd/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec ($ch);
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
if($orderResults){
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
else{
$response[$orderid] = ['status' => 'Order already placed'];
}
echo json_encode($response);
?>

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.

How to get data from a database using a loop?

In my database I've got different username: "fabio97", "antonino", "lauretta". I want to get them from DB to have an array like this:
$dati = array("str"=>array("n1"=>"fabio97", "n2"=>"antonino", "n3"=>"lauretta"));
is it correct write:
...
"str" => array("n".$i=>"Ti sei incrociato con ".$array_db[username]),
...
into a loop
...
$i = 0;
$array_user = mysql_fetch_array($query);
while ($array_db = mysql_fetch_array ($query_db)) {
...
if ($array_user[square] == $array_db[square]) {
$dati = array(
"data" => array(
'address_complete'=>$data->results[0]->formatted_address,
'address_square'=>$data->results[0]->address_components[1]->long_name,
'location'=>$data->results[0]->address_components[2]->long_name,
'postal_code'=>$data->results[0]->address_components[7]->long_name,
'data_ora'=>$tmp_date
),
"str" => array("n".$i=>"Ti sei incrociato con ".$array_db[username]),
"index" => $i
);
$i++;
}
}
and to call them with Ajax:
... success:function(msg){
if(msg){
$("#location").html(Object.keys(msg.str).map(x => msg.str[x]).join(", "));
}else{
$("#location").html('Not Available');
}

Resources