简体   繁体   中英

drupal 8 commerce get product returns empty object

So i have created a few products and added some data to it:

在此处输入图片说明

In my custom route i am then trying to get all products out using the following code:

$products = \Drupal\commerce_product\Entity\Product::loadMultiple();
$response['data'] = $products;
$response['method'] = 'GET';
return new JsonResponse($response);

However this returns the following reponse:

{"data":{"3":{},"6":{},"7":{}},"method":"GET"}

Can anyone tell me what ive done wrong?

The JSON response is not encoding past the first level of depth. As far as I can tell, you cannot control that when using new JsonResponse() .

One solution is to build your own data structure and encode the JSON manually. This solution uses the serializer service: https://drupal.stackexchange.com/a/191474/70331

In your case, something like this should encode the full entity structure.

use Drupal\commerce_product\Entity\Product;
use Symfony\Component\HttpFoundation\JsonResponse;
...

$products = Product::loadMultiple([$ids]);

$response['data'] = $products;
$response['method'] = 'GET';

$serializer = \Drupal::service('serializer');
$jsonResponse = JsonResponse::fromJsonString($serializer->serialize($response, 'json'));
return $jsonResponse;

If using the 'serializer' it is best to provide that to the controller via dependency injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM