Score:0

Extend Commerce api shipping methods response with custom fields

cn flag

With commerce api module, you can fetch all available shipping methods of an order with a GET request on {{host}}/jsonapi/checkout/{{cart_uuid}}/shipping-methods. Result is something like this:

    {
        "type": "shipping-rate-option",
        "id": "3--default",
        "attributes": {
            "shipping_method_id": "3",
            "service": {
                "id": "default",
                "label": "Pickup at location"
            },
            "original_amount": {
                "number": "0",
                "currency_code": "CZK",
                "formatted": "0,00 Kč"
            },
            "amount": {
                "number": "0",
                "currency_code": "CZK",
                "formatted": "0,00 Kč"
            },
            "description": "",
            "delivery_date": null
        }
    },

I would like to add a custom field to each shipping method.

Following this tutorial, I tried to create a computed field, like this:

function custom_module_entity_base_field_info(EntityTypeInterface $entity_type) {

  if ($entity_type->id() === 'commerce_shipment') { // also tried 'shipping_rate_option'
    $fields['tooltip'] = BaseFieldDefinition::create('string')
      ->setLabel(t('tooltip'))
      ->setReadOnly(TRUE)
      ->setComputed(TRUE)
      ->setClass(FieldTooltip::class);

    return $fields;
  }

}

And my class is

/**
 * Class FieldTooltip.
 */
class FieldTooltip extends FieldItemList {

  use ComputedItemListTrait;

  /**
   * {@inheritdoc}
   */
  protected function computeValue() {
    $this->list[0] = $this->createItem(0, 'tooltip text');
  }
}

It did nothing. Also tried to create a normalizer, but that didn't do any change either.

Is there a way to add a field to this response?

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.