I wonder if it is an array that is returned by calling getTable('tbl', 'module') or an object. I am facing problems when I try to insert the returned value into another array and then encode it as JSON. Passing it per se to $this->_helper->json() generates JSON output successfully, but using it as part of another array just does not work and is a null array. See below for the controller code:
//put your code here
public function indexAction () {
}
public function browseAction () {
$resultArray = $this->prepareArray();
$this->sendResponse($resultArray);
}
/**
* HTTP Response Codes
*/
const HTTP_OK = 200;
public function sendResponse($data) {
ob_clean();
$this->_helper->json($data);
}
public function prepareArray() {
//Here we will prepare the array to be later encoded as JSON
$responseArray = [
'status_code' => '',
'body' => [
'itemsCount' => '',
'foods' => [
'food_id' => '',
'food_title' => '',
'image' => '',
],
],
];
$foodTable = Engine_Api::_()->getDbTable('foods', 'restapi');
$foods = $foodTable->getFoods($this->view);
$foodArray = [];
print_r($foods);
while ($row = mysqli_fetch_row($foods)) {
$foodArray['food_id'] = $row['food_id'];
$foodArray['food_title'] = $row['title'];
$foodArray['image'] = $row['image'];
}
error_log( $row ['food_id'] . ',' . $row['title']);
$responseArray['status_code'] = '200';
$responseArray['body']['itemsCount'] = count($foods);
$responseArray['body']['foods']= $foodsArray;
return $responseArray;
}
If everything is set properly, getTable('tbl', 'module') returns object(Module_Model_DbTable_Tbl). This is the model of your database table.
Your particular error is on the line where you're assigning foodsArray variable that isn't defined anywhere. You should have assign foodArray here instead.
$responseArray['body']['foods']= $foodsArray; // should be foodArray
Related
I want to store Auth::user()->id on the default column user_id in the SQL query shown below.
I tried to set put like this but does not send any data to the database.
public function saveLoadingsData() {
//Validate for a valid Post Request
if (isset($_POST['orderNumber']) && isset($_POST['Truck']) && isset($_POST['receiptNumber']) && isset($_POST['items'])) {
// {"orderNumber":"CRS1104200001","agentId":"3","items":[{"itemId":"4","itemName":"Embe","quantity":"13"}]}
$orderNumber = $_POST['orderNumber'];
$items = $_POST['items'];
$receiptNumber = $_POST['receiptNumber'];
$Truck = $_POST['Truck'];
$driverName = $_POST['driverName'];
foreach ($items as $singleItem) {
$data = array('order_no' => $orderNumber,'user_id'=>Auth::user()->id,"receiptNumber" => $receiptNumber, "Truck" => $Truck, "driverName" => $driverName, "pid" => $singleItem['itemId'], "qty" => $singleItem['quantity']);
// print_r($data);
DB::table('loadings')->insert($data);
// return redirect()->back();
}
// return redirect()->back();
echo "Success";
}
My ajax function
$("#btnSaveOrder").on('click', function(e){
var orderNumber=$("#order_no").val();
var receiptNumber=$("#receiptNumber").val();
var Truck=$("#Truck").val();
var driverName=$("#driverName").val();
var jsonData=convertTableToJson();
$.ajax('/api/loading/saveLoadingsData', {
type: 'POST',
data: {
orderNumber:orderNumber,
receiptNumber:receiptNumber,
Truck:Truck,
driverName:driverName,
items:jsonData
},
success: function (data, status, xhr) {
alert("Data Saved");
document.location.reload(true);
},
error: function (jqXhr, textStatus, errorMessage) {
console.log(errorMessage);
}
});
});
var convertTableToJson = function(){
var rows = [];
$('table#tableSelectedItems tr').each(function(i, n){
if (i!=0) {
var $row = $(n);
rows.push({
itemId: $row.find('td:eq(0)').text(),
itemName: $row.find('td:eq(1)').text(),
quantity: $row.find('td:eq(2)').text(),
});
}
});
return rows;
};
My api route
Route::post('loading/saveLoadingsData', 'LoadingController#saveLoadingsData');
Can someone help me?
I recommend you the following
Pass the $request object in your method and log all object, maybe are missing data and for that reason it does not meet the condition:
saveLoadingsData(Request $request){
Log::info(json_encode($request->all()));`
}
Then check your logs files to see the result in /storage/logs/laravel.log
I am making a call to an API and the response is somehow what I expect. However, I want to count the number of elements returned and I can not do it. This is what I think is important from the code.
Call in Vue component
data(){
return {
messages: {}
}
},
loadMessages(){
axios.get("api/messagesmenu")
.then((data) => { this.messages = data.data})
}
Api controller
public function index(){
$messages = Message::all()->where('read_at', NULL);
if(isset($messages)){
foreach($messages as $message){
$from = User::find($message->from_id);
$message->fromPrenom = $from->first_name;
$message->fromNom = $from->last_name;
$message->fromImage = $from->user_image;
}
}else{
$messages = [];
}
return $messages;
}
Type of response from the API
{"3":{"id":560,"from_id":2,"to_id":1,"content":"tgr","created_at":"2019-07-15 16:59:03","read_at":null,"fromPrenom":"abdel1","fromNom":"Hidalgo","fromImage":"user2-160x160.png"}}
I want to count the number of objects I obtain. if (in vue component) I do
this.messages.length
it returns undefined
Try this:
const messages = {"3":{"id":560,"from_id":2,"to_id":1,"content":"tgr","created_at":"2019-07-15 16:59:03","read_at":null,"fromPrenom":"abdel1","fromNom":"Hidalgo","fromImage":"user2-160x160.png"}}
console.log(Object.keys(messages).length) // 1
Or in your code:
...
.then((data) => {
this.messages = data.data
console.log(Object.keys(this.messages).length)
})
Here is my code I tried,
var array=[];
var list = this.state.list;
var getList = function(i){
var add = +i + 1;
return {
["value"+add]:{
Description:list[i].Description,
Length:list[i].Length,
Height:list[i].Height,
Weight:list[i].Weight,
VolumeWeight:list[i].VolumeWeight,
ActualWeight:list[i].ActualWeight,
}
}
}.bind(this)
for(var i in list){
array.push(getList(i));
}
var dataArray = array.map(function(e){
return JSON.stringify(e);
});
dataString = dataArray.join(",");
data1 = {
ConsigneeBranchName:this.state.searchText,
ConsigneeBranchCode:this.state.code,
ConsigneeBranchFullAddress:this.state.DAddress,
SenderBranchCode:this.state.code1,
SenderBranchName:this.state.searchTexts,
SenderBranchFullAddress:this.state.Address,
CreatedByEmployeeCode:id,
CreatedByEmployeeFullName:userName,
jsonString:{
JsonValues:{
id:"MyID",
values:dataString
}
}
}
But I want the result is exactly this
var result = {
"ConsigneeBranchName":"",
"ConsigneeBranchCode":"",
"ConsigneeBranchFullAddress":"",
"SenderBranchCode":"",
"SenderBranchName":"",
"SenderBranchFullAddress":"",
"CreatedByEmployeeCode":"",
"CreatedByEmployeeFullName":"",
"jsonString":"{
"JsonValues": {
"id": "MyID",
"values": {
"value1":{
"Description”:"testSmarter1",
"Length”:"60",
"Height”:"50",
"Weight”:"70",
"VolumeWeight”:"75",
"ActualWeight”:”78"
},
"value2:{
"Description":"Documents",
"Length":"120",
"Height":"68",
"Weight":"75",
"VolumeWeight":"122.4",
"ActualWeight":"123"
},
}
}
}
};
Please any one help me
I want the object with dynamic keys within a single object {key1:{des:1,value:as},key2:{des:2,value:aw},key3:{des:3,value:au}}
can you please help me I have tried so many times
see this below image I want this part, inside the single object, I can join multiple objects with dynamic keys
lodash already has a function called keyBy, you can use it to get this functionality. If adding lodash doesn't make sense in your project.
I have implemented a vanilla JS version.
function keyBy(array, mapperFn) {
const resultObj = {};
array.map(item => resultObj[mapperFn(item)] = item);
return resultObj;
}
function arrayToObject (array, keyName = 'id') {
return keyBy(array, function(element) {return element[keyName]});
}
API:
arrayToObject(targetArray, stringNameOfThePorpertyYouWantToUseAsKey);
USAGE:
const listOfUsers = [{name: 'Jenitha', reputation: 6}, {name: 'Chandan', reputation: 3}];
const mapOfUsersByName = arrayToObject(listOfUsers, 'name');
I am working on yii2. I have came across a point in which I have to send an email to a person when a meter is installed and it's images are uploaded to the server. Fro this I have already configured the swift mailer.
There is a model named Installations which have a function which saves all the installation data.
public static function saveAll($inputs){
$coutner = 0;
$arr_status = [];
foreach ($inputs as $input) {
$s = new Installations;
foreach ((array)$input as $key => $value) {
if($key != 'image_names') {
if ($s->hasAttribute($key)) {
$s->$key = $value;
}
}
}
$user = Yii::$app->user;
if (isset($input->auth_key) && Users::find()->where(['auth_key' => $input->auth_key])->exists()) {
$user = Users::find()->where(['auth_key' => $input->auth_key])->one();
}
$s->created_by = $user->id;
if (Installations::find()->where(['ref_no' => $input->ref_no])->exists()) {
$arr_status[] = ['install_id' => $input->install_id, 'status' => 2, 'messages' => "Ref # Already exists"];
continue;
}
$s->sync_date = date('Y-m-d H:i:s ');
if($s->save()){
if ($s->istallation_status == 'Installed') {
Meters::change_status_byinstall($s->meter_msn, Meters::$status_titles[4]);
}
else if ($s->istallation_status != 'Installed' && $s->comm_status =='Failed')
{
Meters::change_status_byinstall($s->meter_msn, Meters::$status_titles[5]);
}
$arr_status[] = ['install_id' => $input->install_id, 'status' => 1];
$coutner++;
if (isset($input->doc_images_name)) {
foreach ($input->doc_images_name as $img) {
$image = new InstallationImages;
$image->image_name = $img->image_name;
$image->installation_id = $s->id;
$image->save();
}
}
if (isset($input->site_images_name)) {
foreach ($input->site_images_name as $img2) {
$image2 = new InstallationImagesSite;
$image2->image_name = $img2->image_name;
$image2->installation_id = $s->id;
$image2->save();
}
}
}else{
$arr_status[] = ['install_id' => $input->install_id, 'status' => 0, 'messages' => $s->errors];
}
$status = $s->istallation_status;
$msn = $s->meter_msn;
$com = $s->comm_status;
// want to pass these variables to the controller function
}
return ['status' => 'OK', 'details' => $arr_status, 'records_saved' => $coutner];
}
Now There Is a Controller name InstallationController. This controller contains all the APIs for my mobile application. Below are two main functions in it
public function actionAddnew()
{
$fp = fopen('debugeeeeeee.txt', 'w+');
fwrite($fp, file_get_contents('php://input'));
fclose($fp);
$inputs = json_decode(file_get_contents('php://input'));
return Installations::saveAll($inputs);
}
public function actionSavephoto()
{
try {
$count = 0;
foreach ($_FILES as $f) {
$dd = pathinfo($f['name']);
if (!isset($dd['extension']) || !in_array($dd['extension'], array('jpg', 'png', 'gif'))) {
return ['status' => 'ERROR', 'uploaded_files' => $count, 'message' => 'Invalid File'];
break;
}
if (move_uploaded_file($f['tmp_name'], Installations::UPLOAD_FOLDER . $f['name'])) {
$count++;
return ['status' => 'OK', 'uploaded_files' => $count];
break;
} else {
return ['status' => 'ERROR', 'uploaded_files' => $count];
break;
}
}
} catch (Exception $x) {
return ['status' => 'ERROR', 'message' => $x->getMessage()];
}
}
The mobile application will call the Addnew() api and after that it will call the savephoto. Now I want to pass $msn,$status and $com values from the Model to the controller function Savephoto.
For this I have tried to use session variables but still I am unable to get by desired result(s).
I have also checked the question Yii, how to pass variables to model from controller?
but it didn't worked for me.
How can I achieve it?
Any help would be highly appreciated.
The only way to get those values out of saveAll() is to return them. Presently, they are defined on an object in $s that is overwritten each loop. The best way to do that seems to be creating an array outside of your foreach ($inputs... loop and appending each created Installations object.
Return that at the end, and pass it (or just the relevant element from it) into actionSavephoto() as a parameter. Then, those values will be accessible of properties of that passed object. This handling will occur in the code that is not pictured which calls actionAddNew() and then actionSavephoto()
In Joomla 1.5 constructor of JDocumentPDF class has an array parameter to setup some parameter of generated PDF.
function __construct($options = array()) {
parent::__construct($options);
if (isset($options['margin-header'])) {
$this->_margin_header = $options['margin-header'];
}
if (isset($options['margin-footer'])) {
$this->_margin_footer = $options['margin-footer'];
}
if (isset($options['margin-top'])) {
$this->_margin_top = $options['margin-top'];
}
...
}
_createDocument() function of JFactory class instantiates JDocumentPDF object, but doesn't pass any options that useful for PDF generation:
function &_createDocument() {
...
$attributes = array (
'charset' => 'utf-8',
'lineend' => 'unix',
'tab' => ' ',
'language' => $lang->getTag(),
'direction' => $lang->isRTL() ? 'rtl' : 'ltr'
);
$doc =& JDocument::getInstance($type, $attributes);
return $doc;
}
So I don't understand how it works and where can I set this options (margin-header, margin-footer etc)?
To set and get any properties of JDocumentPDF
you can call set and get function on object. For example
$obj = JFactory::getDocument();
$marginHeader = $obj->get('_margin_header');
$obj->set('_margin_header', $value);