7

I have a custom admin grid, which lists only the orders that contain the product given as a URL parameter.

My URL is of form https://www.example.com/admin/mymodule/orders/index/product_id/123/

I have defined a custom data provider for the grid in view/adminhtml/ui_components/myvendor_mymodule_order_listing.xml

The admin page itself works fine, and I get the correct orders when I use a hard-coded product id inside the data provider.

I'm however not able to figure out how to pass the product id into the data provider from the URL.

The actual data for the grid is fetched using AJAX, so perhaps the parameter should somehow be included into that request? Or are there some other ways to achieve it?

1

2 Answers 2

0

Within your PHP data provider class, you can inject the RequestInterface and then filter out your order items by retrieving only the ones that match that id from that query parameter:

public function __construct(
    private \Magento\Framework\App\RequestInterface $request
) {
    ...
}

public function getData(): array
{
    if (!isset($this->loadedData)) {
        $this->loadedData = [];

        $items = $this->collection->getItems();
        $productId = $this->request->getParam('product_id');

        foreach ($items as $item) {
            if ($item->getProductId() === $productId) {
                $this->loadedData[$item->getData('id')] = $item->getData();
            }
        }
    }

    return $this->loadedData;
}
0

You can pass the product id from the URL to the data provider by using the request object in your data provider class. Here's a step-by-step guide:

  1. Inject \Magento\Framework\App\RequestInterface in your data provider class. This will allow you to access the request parameters.

  2. Use the getParam method of the request object to get the product id from the URL.

Here's how you can do it:

namespace MyVendor\MyModule\Model;

use Magento\Framework\App\RequestInterface;

class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider
{
    protected $request;

    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        RequestInterface $request,
        array $meta = [],
        array $data = []
    ) {
        parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
        $this->request = $request;
    }

    public function getData()
    {
        $productId = $this->request->getParam('product_id');
        // Now you can use $productId to filter your collection

        // Your existing code here
    }
}

This code will inject the RequestInterface into your data provider and use it to get the product_id parameter from the URL. You can then use this product ID to filter your collection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.