I am using Magento 2.3.3 and GraphQL to get a list of products.
I want to query products by a custom attribute that I created in the admin. Couldn't find in the documentation how to.
It is possible..?
Thanks!
I am using Magento 2.3.3 and GraphQL to get a list of products.
I want to query products by a custom attribute that I created in the admin. Couldn't find in the documentation how to.
It is possible..?
Thanks!
Magento 2.4
Filter, sort, and get product custom attribute
Create Custom Attribute with below options values.
app/code/VendoreName/ModuleName/etc
schema.graphqls
interface ProductInterface {
sample_attribute: String @doc(description: "Product Custom Attribute Show")
@resolver(
class: "VendoreName\\ModuleName\\Model\\Resolver\\Product\\AddCustomAttribute"
)
}
input ProductAttributeFilterInput {
sample_attribute: FilterEqualTypeInput @doc(description: "Product Data filter with Custom Attribute Value")
}
input ProductAttributeSortInput {
sample_attribute: SortEnum @doc(description: "Sort by the Product Custom Attribute.")
}
app/code/VendoreName/ModuleName/Model/Resolver/Product
AddCustomAttribute.php
<?php
namespace VendoreName\ModuleName\Model\Resolver\Product;
use Magento\Framework\GraphQl\Query\ResolverInterface;
/**
* Product custom attribute field resolver
*/
class AddCustomAttribute implements ResolverInterface
{
/**
* @var Magento\Catalog\Model\ProductFactory
*/
protected $productFactory;
/**
* @param Magento\Catalog\Model\ProductFactory $productFactory
*/
public function __construct(
\Magento\Catalog\Model\ProductFactory $productFactory
) {
$this->productFactory = $productFactory;
}
/**
* @inheritdoc
*/
public function resolve(
\Magento\Framework\GraphQl\Config\Element\Field $field,
$context,
\Magento\Framework\GraphQl\Schema\Type\ResolveInfo $info,
array $value = null,
array $args = null
) {
$product = $value['model'];
$_product = $this->productFactory->create()->load($product->getId());
return $_product->getData('sample_attribute');
}
}
Run Magento Commands:
php bin/magento s:up
php bin/magento in:rein
php bin/magento s:s:d -f
php bin/magento c:c
For show product custom attribute value
{
products(filter: { sku: { eq: "24-MB01" } }) {
items {
name
sku
sample_attribute
}
}
}
For filter product data using custom attribute
{
products(filter: { sample_attribute: { eq: "test" } }) {
items {
name
sku
sample_attribute
}
}
}
For sort product data using custom attribute
{
products(search: "bag", sort: {sample_attribute: DESC}) {
items {
name
sku
sample_attribute
}
}
}
Okay got the solution..