API Json in symfony form - json

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

Related

Render view and new JSON response in symfony controller

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')
);

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}}

How to create a new input field which would offer values stored in different database table? Yii2

It's pretty hard to formulate the question correctly, but I'll try to explain it more here. I have an Item, Category and Sale models. In category and Item models I manually stored data. Now I've created a form, which has some input fields and dependent drop-down, which is:
According to the selected category, items are loaded.
Now I need to create a new input field, which would be price and it has to be taken from the database as a offer (f.e if the user selects Item1 -> Item1 price has to be loaded up as a offer in the input field, which I could edit it and store in different database table.
How should I do that?
Here is my SaleController action:
/**
* Creates a new sale
*
* #return string
*/
public function actionCreate()
{
$model = new Sale();
$model->scenario = Sale::SCENARIO_CREATE;
$category = new Category();
$category->scenario = Category::SCENARIO_CREATE;
$categoryList = ArrayHelper::map(Category::find()->all(), 'id', 'name');
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
return $this->redirect(['index']);
}
}
return $this->render('create', [
'model' => $model,
'category' => $category,
'categoryList' => $categoryList,
]);
}
And here is my view:
<?= $form->field($category, 'id')->dropDownList($categoryList, [
'id' => 'category-id',
'prompt' => 'Choose a category',
]); ?>
<?= $form->field($model, 'item_id')->widget(DepDrop::classname(), [
'options'=>['id'=>'item-id'],
'pluginOptions'=>[
'depends'=>['category-id'],
'placeholder'=> 'Choose an item',
'url'=>Url::to(['/sale/subcat'])
]
]); ?>
<?= $form->field($model, 'price') ?>
Thank you for any help. I hope you understand the question
First you must add an input field in your view from model:
<?= $form->field($model, 'item_price')->textInput([
'maxlength' => true,
'id' => 'input-price-id'
]) ?>
Then you need to add some javascript:
<?php
$item_price=<<<JS
$('#item-id').on('change', function(event) {
var id = $(this).attr('id');
var val = $(this).val();
.get(
// you must code function actionRefreshPrice wtih parameter named item_id in
// your controller with fetch from any table you want
'refresh-price',
{
item_id: val // this is id from your item
},
function (data) {
// here you set a value returned from ajax call
// you must have an input element with id input-price-is (change as you like)
$('#input-price-id').val(data);
}
);
});
JS;
$this->registerJs($item_price);
?>
Then you must add a controller action something like this:
public function actionRefreshPrice($item_id) {
// I asume you have table with Price for items prices
$price = Price::findOne(['item_id'=>$item_id]);
return ($price?0:$price->price_field);
}
I hope I have given you enough guidelines. And a comment learn more about models and relations. I think you overthought problem a little bit. Happy learning and coding.

Yii2 POST image to model in API without Yii2 Naming convention

I'm creating an endpoint for a mobile application to send a image to the server. I'm posting the image with the POSTMAN extension for chrome. The image is in the $_FILES variable, and named image. How can I load this image into a model, or the UploadedFile class? The $model->load(Yii::$app->request->post()) line does not correctly load the file, as it is not in Yii2's naming convention for forms.
It's currently returning:
{
"success": false,
"message": "Required parameter 'image' is not set."
}
Code
models\Image.php
<?php
namespace api\modules\v1\models;
use yii\base\Model;
use yii\web\UploadedFile;
class Image extends Model
{
/**
* #var UploadedFile
*/
public $image;
public function rules()
{
return [
[['image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
$path = dirname(dirname(__FILE__)) . '/temp/';
if ($this->validate()) {
$this->image->saveAs($path . $this->image->baseName . '.' . $this->image->extension);
return true;
} else {
die(var_dump($this->errors));
return false;
}
}
}
controllers\DefaultController.php
<?php
namespace api\modules\v1\controllers;
use api\modules\v1\models\Image;
use yii\web\Controller;
use yii\web\UploadedFile;
use Yii;
class DefaultController extends Controller
{
public $enableCsrfValidation = false;
public function actionIndex()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = new Image();
if (Yii::$app->request->isPost) {
if($model->load(Yii::$app->request->post()))
{
$model->image = UploadedFile::getInstance($model, 'image');
if ($model->upload()) {
// file is uploaded successfully
return ['success' => true, 'message' => 'File saved.'];
}
else return ['success' => false, 'message' => 'Could not save file.'];
}
else return ['success' => false, 'message' => 'Required parameter \'image\' is not set.'];
}
else return ['success' => false, 'message' => 'Not a POST request.'];
}
}
Postman
Your problem seems to be the name you are using to send the image file. Usually Yii2 uses names for form attributes like "ModelName[attributeName]" and you are sending your image file with the name "image"
There are 2 ways of fixing this:
Change the name you use to send your image file to follow the same naming conveniton. However you don't seem to want that.
Use getInstanceByName('image') method instead of getInstance($model, 'image')
The problem come here
When you send files via api they are not sent asynchronously. If you check
echo '<pre>';
print_r($_FILES); //returns nothing
print_r($_POST["image"]); //returns something
echo '</pre>';
die;
One reason is that your controller extendsyii\web\controller which is not used by rest apis, extend yii\rest\controller
The other way to go about this is by using javascript formData when sending the post request
This is a way i handled a previous ajax post of an image probably itll give you a guideline
The form
<?php $form = ActiveForm::begin(['options' => ['enctype' =>
'multipart/form-data','id'=>'slider_form']]); ?> //dont forget enctype
<?= $form->field($model, 'file')->fileInput() ?>
Then on the ajax post
var formData = new FormData($('form#slider_form')[0].files);
$.post(
href, //serialize Yii2 form
{other atributes ,formData:formData}
)
Then on the controller simply access via
$model->file =$_FILES["TblSlider"]; //here this depends on your form attributes check with var_dump($_FILES)
$file_tmp = $_FILES["TblSlider"]["tmp_name"]["file"];
$file_ext = pathinfo($_FILES['TblSlider']['name']["file"], PATHINFO_EXTENSION);
if(!empty($model->file)){
$filename = strtotime(date("Y-m-d h:m:s")).".".$file_ext;
move_uploaded_file($file_tmp, "../uploads/siteimages/slider/".$filename);
///move_uploaded_file($file_tmp, Yii::getAlias("#uploads/siteimages/slider/").$filename);
$model->image = $filename;
}
I hope this helps

Can't get count of a json array from symfony 2.7 via ajax call

I need to get the count of a JSON array returned by symfony 2.7 controller action.
This is my controller
<?php
namespace Eagle\ShopBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
class CartController extends Controller {
/**
* #Route("/cart/add")
* #Template()
*/
public function addAction(Request $request) {
$items = Array(
166 => Array(
'quantity' => 2,
'price' => 7
),
165 => Array(
'quantity' => 1,
'price' => 7
)
);
//convert to json using "JMSSerializerBundle"
$serializer = $this->container->get('serializer');
$jsonproducts = $serializer->serialize($items, 'json');
return new Response($jsonproducts);
}
}
And this is my ajax call,
$.post("http://localhost:8000/cart/add", function (data) {
alert(data.length);
});
I need to get the count of items from array(2), but I get 63 inside alert box.
As I see, you got string in response. You need smth like:
$.post("http://localhost:8000/cart/add", function (data) {
var json = $.parseJSON(data); //parsing response string into JSON Object
var length = Object.keys(json).length; //A little bit crappy way to get JSON Object length, but it works
alert(length);
});
Or, of course you could use the way provided by #Put12co22mer2 - it is even better.
If you return a response , the 63 is the number of chars in the string (actually the response is a html string) ... You've to return a JsonResponse
You don't need the #Template()
Something like :
<?php
namespace Eagle\ShopBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse; // <---- LOOK HERE
class CartController extends Controller {
/**
* #Route("/cart/add")
*/
public function addAction(Request $request) {
$items = Array(
166 => Array(
'quantity' => 2,
'price' => 7
),
165 => Array(
'quantity' => 1,
'price' => 7
)
);
return new JsonResponse($jsonproducts); // <---- LOOK HERE
}
}