Render view and new JSON response in symfony controller - json

I'm having an issue rendering a Twig view and a JSON response, I need to call the twig view and pass it a new Json response with a variable as parameter. The output error is the following "Notice: Object of class Symfony\Component\HttpFoundation\Response could not be converted to int
"
Here is the code
$resultado = array('mes1_local' => $mes1_local, 'mes2_local' => $mes2_local, 'mes3_local' => $mes3_local, 'mes1_online' => $mes1_online, 'mes2_online' => $mes2_online, 'mes3_online' => $mes3_online, 'contador_pedido_local' => $contador_pedido_local, 'contador_pedido_online' => $contador_pedido_online, 'contador_total' => $contador_total, 'contador_usuarios' => $contador_usuarios);
return new JsonResponse($resultado, $this->render('others/adminlte.html.twig'));

Like #goto's answer, but it won't works, cause you need to use renderView instead of render:
return new JsonResponse([
'things' => $thingsArray,
'anotherVariable' => $simpleVariable,
'html' => $this->renderView('others/adminlte.html.twig', []/* template parameters goes here */),
]);

The Json Response signature is
__construct(mixed $data = null, int $status = 200, array $headers = array(), bool $json = false)
You are trying to give the twig to the status parameter.
You can avoid this silly error by using a good IDE
To give additional data to your response you could structure your array data returned
return new JsonResponse([
'someData' => $resultado,
'html' => $this->render('others/adminlte.html.twig')
);

Related

How to save data json from api external to database in laravel

i want to generate reports from api external, using guzzle, here is my result
{#430 ▼
+"data": {#427 ▼
+"report_id": "20190801-5f6e21a5"
+"status": 5
+"creation_date": "2019-08-01 13:19:49"
+"due_date": "2019-08-02 13:19:49"
+"data": {#432 ▼
+"chassis_number": "ACR50-0183692"
+"engine": "2AZFE"
+"manufacture_date": "2014-07"
+"registration_date": "2019-04-17"
+"make": "TOYOTA"
+"model": "ESTIMA"
+"displacement": "2360"
+"fuel": "GASOLINE"
}
}
+"error": ""
}
but i dont know how to get the value from this json and save to database. i want to save value from report_id, status, creation date etc
$client = new Client();
$body = $client->request('GET', 'https://xxxxx/api/v1/get-report', [
'headers' => [
'Accept' => 'application/json',
'Carvx-User-Uid' => 'xxxxxx',
'Carvx-Api-Key' => 'xxxxxx',
'needSignature' => '0',
'raiseExceptions' => '1',
'isTest' => '0'
],
'query' => [
'report_id' => $reportId,
'true'=>'1'
]
])->getBody();
$contents = (string) $body;
$data = json_decode($contents);
// dd($data);
//to get value from status
$var_status = var_export($data['status'],true);
$status = substr($var_status, 1, -1);
echo $status;
and i get this error
Cannot use object of type stdClass as array
json_decode by default returns a Stdclass object, with properties representing the keys in the json object.
You can tell json_decode to return an associative array instead by passing true as the second param:
json_decode($contents, true); // returns array
Docs: https://www.php.net/manual/en/function.json-decode.php

Add new attribute dynamically to the existing model object in Yii2 framework

In Yii2 framework is it possible to add a new attribute dynamically to an existing object, which is retrieved from Database?
Example
//Retrieve from $result
$result = Result::findone(1);
//Add dynamic attribute to the object say 'result'
$result->attributes = array('attempt' => 1);
If it is not possible, please suggest an alternate best method to implement it.
Finally I would be converting the result to a json object. In my application, at the behaviour code block, I have used like this:
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
You can add define a public variable inside your model, that will store dynamic attributes as associative array. It'll look something like this:
class Result extends \yii\db\ActiveRecord implements Arrayable
{
public $dynamic;
// Implementation of Arrayable fields() method, for JSON
public function fields()
{
return [
'id' => 'id',
'created_at' => 'created_at',
// other attributes...
'dynamic' => 'dynamic',
];
}
...
..in your action pass some dynamic values to your model, and return everything as JSON:
public function actionJson()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = Result::findOne(1);
$model->dynamic = [
'field1' => 'value1',
'field2' => 2,
'field3' => 3.33,
];
return $model;
}
In result you will get JSON like this:
{"id":1,"created_at":1499497557,"dynamic":{"field1":"value1","field2":2,"field3":3.33}}

Returning multiple JSON from controller in Laravel

I have something like this in the route:
Route::post('/iteminfo/{item_id}','itemcontroller#get_item_info');
And something like this in the controller
public function get_item_info($request)
{
$item_image = Item_Image->where("item_id",$request)->first();
$item_something = Item_Something->where("item_id",$request)->first();
$item_more = Item_More->where("item_id",$request)->first();
return Response::json($item_image);
}
I want to return the 3 things but with return Response::json() I can only return 1 statement (as far as I know). Is there any way to return all of them?
You can pass an array as the json response. So craft an array based on your data and use it.
return Response::json(array(
'item_image' => $item_image,
'item_something' => $item_something,
'item_more' => $item_more,
));
Since it requires an Array parameter so you can construct an array from the variables
return response()->json(['item_image ' => $item_image, 'item_something' => $item_something, 'item_more' => $item_more ]);
Or
return Response::json(['item_image ' => $item_image, 'item_something' => $item_something, 'item_more' => $item_more ]);

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

NULL value is saving in database instead of user submitted info

I am new to laravel and I am facing following problem
My problem
Problem i m facing is that whenever I submit the form after filling firstname lastname and phone, then everything going well except one thing that in my MYSQL database data is save as firstname: NULL lastname:NULL And phone:NULL instead of saving the data which i had enter.
I have a angularjs form in which is there fields like firstname lastname and phone.on submit it goes to submitContact() in controller:
submit.js:
var addnew = angular.module('addnew',[]);
// create angular controller
addnew.controller('addContactController',
function($scope,$location,$window,$http) {
// function to submit the form after all validation has occurred
$scope.submitContact = function() {
$scope.addnew = {firstname:'', lastname:'',phone:''};
$scope.addnew.firstname=$scope.firstname;
$scope.addnew.lastname=$scope.lastname;
$scope.addnew.phone=$scope.phone;
$http.get("http://localhost:8000/index.php/user/addnew",{"firstname": $scope.firstname, "phone": $scope.phone, "lastname": $scope.lastname})
.then(function mysuccess(response) {
$scope.mycard = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statustext;
$window.alert(JSON.stringify(response));
console.log(response.data);
});
};
});
http://localhost:8000/index.php/user/addnew this links to my laravel through routes.
my route.php:
Route::get('/user/addnew', 'usercontroller#store');
my usercontroller.php
public function store(Request $request)
{
//contacts::create(Request::all());
$user = new contacts;// contacts is my table name and my database is defined in .env file
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->phone = Input::get('phone');
$user->save();
//I Used print_r to see that weather my submitted data is coming in $user or not:
print_r($user);
echo "saved";
}
my contact.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class contacts extends Model
{
protected $fillable =['firstname','lastname','phone'];
}
?>
Now, My problem
when i print_r $user then i got the error as my array is NOT catching my submitted data
print_r ($user) output in console window:
[fillable:protected] => Array
(
[0] => firstname
[1] => lastname
[2] => phone
)
[connection:protected] =>
[table:protected] =>
[primaryKey:protected] => id
[keyType:protected] => int
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[firstname] =>
[lastname] =>
[phone] =>
[updated_at] => 2016-10-07 03:46:34
[created_at] => 2016-10-07 03:46:34
[id] => 38
)
[original:protected] => Array
(
[firstname] =>
[lastname] =>
[phone] =>
[updated_at] => 2016-10-07 03:46:34
[created_at] => 2016-10-07 03:46:34
[id] => 38
)
I want to know where I m making mistake and how can I correct that mistake.
Thanking you in anticipation.
Try this:
$user = new Contact();
Instead of this:
$user = new contacts;
Also, change class name to class Contact extends Model and a filename to a Contact.php.
Alternatively, since you're using $fillable you can create new row:
Contact::create($request->all());
https://laravel.com/docs/5.3/eloquent#mass-assignment
I think you should use POST instead of GET.
$http.post("http://localhost:8000/index.php/user/addnew",{"firstname": $scope.firstname, "phone": $scope.phone, "lastname": $scope.lastname})
.then(function mysuccess(response) {
$scope.mycard = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statustext;
$window.alert(JSON.stringify(response));
console.log(response.data);
});
And
Route::post('/user/addnew', 'usercontroller#store');
And I noticed that you are posting to /index.php/user/addnew
And your route is '/user/addnew'
'/index.php/user/addnew' and '/user/addnew' are different.
try posting to localhost:8000/user/addnew instead
To explain:
/user/addnew always refer to host:port/user/addnew
While user/addnew will just concatenate it to your current url
for example if you're currently at: localhost:8000/users/1
Clicking a link to user/addnew will bring you to localhost:8000/users/1/user/addnew while a link to /user/addnew will bring you to localhost:8000/user/addnew
EDIT:
Is this redundant?
$scope.addnew.firstname=$scope.firstname;
$scope.addnew.lastname=$scope.lastname;
$scope.addnew.phone=$scope.phone;
What you were sending is this:
{"firstname": $scope.firstname, "phone": $scope.phone, "lastname": $scope.lastname}
I think you can send this instead:
$scope.addnew
and again, you should use POST, not GET.
did you already update your http request to post? did you update the url?
Actually, I achived this by using $request->input('firstname'); $request->input('firstname'); $request->input('firstname');, since, it was JSON thats why. Else, If I had been using Laravel blade file then I could have done it by above solutions.