Kindly check json response from one to many relation. I want to show this response in ajax. But i don't know how to show in ajax. how to show in success response.
{
"extra":{
"values":[
[
{
"id":9,
"extra_name":"Ihr Dip:",
"status":"open",
"created_at":"2022-04-19T16:47:35.000000Z",
"updated_at":"2022-04-19T16:47:35.000000Z",
"created_by":"1",
"updated_by":null,
"extra":[
{
"id":17,
"description":"mit Kr\u00e4uter-Remoulade",
"status":"open",
"main_extra_id":"9",
"price":"1,00",
"created_at":"2022-04-19T16:47:55.000000Z",
"updated_at":"2022-04-19T16:47:55.000000Z",
"created_by":"1",
"updated_by":null
},
{
"id":18,
"description":"mit Pizza Max Ketchup 40ml",
"status":"open",
"main_extra_id":"9",
"price":"10,70",
"created_at":"2022-04-19T16:48:14.000000Z",
"updated_at":"2022-04-19T16:48:14.000000Z",
"created_by":"1",
"updated_by":null
}
]
}
]
]
}
}
Laravel will automatically serialize your Eloquent models and collections to JSON when they are returned from routes or controllers:
Route::get('users', function () {
return User::all();
});
See below link:
https://laravel.com/docs/9.x/eloquent-serialization#relationships
Another example:
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index(){
return Post::latest()
->with('category', 'author')->get();
}
}
Related
Good Day!
I am planning to create a custom API for Account module were I am going to get and update data using API. I created a custom field (integration_ref_id) on my Account module this will serve as my identifier if the accounts is existing or not. Check bellow as payload request sample
{
"consent_timestamp": "2021-04-13 09:45:00",
"integration_ref_id": "CUSREF-202104-ABCDEF0000003",
"last_name": "De la Cruz",
"first_name": "Juan",
"birthdate": "1995-03-25",
"mobile_number": "+639171234199",
"email": "juan.delacruz#example.com",
"location_code": "LOC0001",
"street_name": "Rose St.",
"landmarks": "Mcdo",
"gender": "male"
}
Now I created custom routes on my custom folder (custom/application/Ext/Api/V8/Config)
<?php
$app->get('/my-route/{myParam}', 'MyCustomController:myCustomAction');
$app->get('/hello', function() {
return 'Hello World!';
});
$app->get('/getCustomers', 'Api\V8\Controllers\CustomersController:getCustomers');
And I place the controller same path of the routes. (custom/application/Ext/Api/V8/Controller)
And this is my controller code
<?php
namespace Api\V8\Controller;
if (!defined('sugarEntry') || !sugarEntry) {
die('Not A Valid Entry Point');
}
class CustomersController extends BaseController
{
public function getCustomers(Request $request, Response $response, array $args, GetRelationshipParams $params)
{
try {
$jsonResponse = $this->relationshipService->getCustomers($request);
return $this->generateResponse($response, $jsonResponse, 200);
} catch (\Exception $exception) {
return $this->generateErrorResponse($response, $exception, 400);
}
}
}
But I got this Error in postman
I keep searching, but its kinda confusing on my end. BTW I am new on this SuiteCRM
Regards!
Never mind, I was able to figure it out. I just added this code below to my controller CustomeController.php
namespace Api\V8\Controller;
use Slim\Http\Response;
use Slim\Http\Request;
And added this one to my custom controller.php
require 'custom/application/Ext/Api/V8/Controller/CustomersController.php';
use Api\V8\Controller;
use Slim\Container;
Then everything should be working.
List with Views published nodes in the form of a table. Add to a table with a column that will contain a link. By clicking on the link ajax request should be sent, which makes the node unpublished.
I have views, have a link, have alert-ajax. But I don't understand how I can change the status from 0 to 1 programmatically.
My code in controller -
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\RemoveCommand;
use Drupal\Core\Controller\ControllerBase;
class CustomAjaxLinkController extends ControllerBase{
public function customAjaxLinkAlert($node) {
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$node = $query->execute();
$status = $node-> isPublished();
if ($status === TRUE) {
$node->status = 0;
$node->save();
}
$response = new AjaxResponse();
$selector = '.customAjaxLinkAlert' ;
$response->addCommand(new RemoveCommand($selector, $node));
return $response;
}
}
There is an error in it, but I cannot figure out what I am doing wrong
You can past data's via ajax in a Drupal Controller
$.ajax({
type: 'POST',
url: '/your_module/your_function',
data: {'data': data},
});
Then in your Controller
<?php
namespace Drupal\your_module\your_contoller;
use Drupal\Core\Controller\ControllerBase;
/**
* Class your_contoller.
*/
class your_contoller extends ControllerBase {
public function your_function() {
do what you want
}
}
OR
Your button is inside a form and will submit the value.
i tried to set $uses in cakePhp3, it's working in cakePhp2.6 but not in 3
public $uses = array('model1', 'model2', 'model3', .... );
but i get error like
{
"message": "Call to a member function find() on boolean",
"url": "/JobPosts/Test/1042.json",
"code": 500,
"file": "/home/task24/public_html/clientApi/src/Controller/JobPostsController.php",
"line": 1304
}
You don't use $uses anymore in Cake 3.
$this->loadModel('MyModel');
Try to load all models using array_map function
array_map([$this, 'loadModel'], ['Product', 'Orders', 'OrderItem']); //Pass each element of the array to loadModel with is accessable through $this object.
Or create a function in your AppController, like
function loadModels($models = []) {
foreach($models as $model) {
$this->loadModel($model);
}
}
//Then you can access this function anywhere from any controller function (Controller which are extending AppController)
$this->loadModels(['Products', 'Orders', 'SO-ON']);
I intend to map the output from external api to object attribute in model.
For examples, data->x to Device->$attribute_x;, data->y to Device->$attribute_y; The output is array of objects.
My expected outcome is extract each of object by access the Device model and its attributes and do some manipulation in model. (fetch once time only from API and format it in different function)
Can someone give some guideline on ways to defining methods/class to achieve?
This is my output from external API:
{
"data": [
{
"x": "1",
"y": "2"
},
{
"x": "11",
"y": "22"
}
]
}
This is model without extend Eloquent in Laravel to extract all data from external API using guzzle .
namespace App;
$client = new \GuzzleHttp\Client([
'base_uri' => 'https://xxxx.com',
'headers' => [
'content_type' => 'application/json',
'accept' => 'application/json'
]]);
$response = $client->get('units');
$data = json_decode($response->getBody());
class Devices
{
protected $attribute_x;
protected $attribute_y;
public static function all(){
}
}
I write code from head, but you can create in Devices following method:
public static function importFromAPI($data) {
$result = [];
foreach($data as $item) {
$dev = new Device;
$dev->attribute_x = $item['x'];
$dev->attribute_y = $item['y'];
$result[] = $dev;
}
return $result;
}
And use it to import Device list from data array from API json
$devices = Devices::importFromAPI($data);
Your Device can extend eloquent Model class as well to have easy access to DB. Above method can be also implemented in separate class e.g ApiService and be renamed to importDevicesFromAPI and contains code to load json and map it to Device objects.
I made an API call and received the response in JSON format.
JSON:
{
"Specialities": [
{
"SpecialityID": 1,
"SpecialityName": "Eye Doctor"
},
{
"SpecialityID": 2,
"SpecialityName": "Chiropractor"
},
{
"SpecialityID": 3,
"SpecialityName": "Primary Care Doctor"
}
]
}
Controller File:
public function index(){
$data= json_decode(file_get_contents('some_url'));
$this->load->view('my_view',$data);
}
Above code doesn't work because in view I can't access the nested object properties. However I am able to echo the JSON properties in controller file just like this:
Controller File:
public function index(){
$data=json_decode(file_get_contents('some_url'));
foreach ($data as $key=>$prop_name){
for($i=0;$i < count($prop_name);$i++){
echo $prop_name[$i]->SpecialityID;
echo $prop_name[$i]->SpecialityName;
}
}
}
My question is how do I pass this JSON to view and how can I access those properties in view file?
In controller changes like
public function index(){
$data['json_data']= json_decode(file_get_contents('some_url'));
$this->load->view('my_view',$data);
}
and in the view
echo "<pre>";print_r($json_data);
As per Docs
Data is passed from the controller to the view by way of an array or
an object in the second parameter of the view loading method.
Here is an example using an array:
So you need to change your code in controller
Controller.php
$data = array();
$data['myJson'] = json_decode(file_get_contents('some_url'));
$this->load->view('my_view',$data);
my_view.php
<html>
....
<?php
//Access them like so
print_r($myJson);
// Rest of your code here to play with json
?>
....
</html>