Displaying Yes/No Attribute in Magento Custom Product Grid
Are you struggling to display yes/no values from your custom product attribute in a grid view? You’re not alone! In this guide, we’ll walk through the steps to correctly show yes or no in your Magento custom product grid.
Understanding the Issue
You’ve successfully retrieved the 0 and 1 values for your yes/no attribute from the database. However, you want to display these as user-friendly options - ‘Yes’ instead of ‘1’, and ‘No’ instead of ‘0’.
The Problem with Existing Code
In your current Grid.php file, you’re using a simple if statement to check the value:
$this->addColumn(
'show_yes_no',
[
'header_text' => 'Show Yes/No',
'index' => 'attribute_id', // Replace this with your actual attribute ID
'type' => 'options',
'options' => [
0 => 'No',
1 => 'Yes'
]
]
);
While this looks good, it assumes that the value will always be an integer. If someone manually enters a string like “yes” or “no”, your grid won’t display correctly.
The Solution: Use Column Filters
To handle both integers and strings, we’ll use column filters to standardize the input before displaying it:
- Add a new filter:
$this->addFilter(
'show_yes_no',
[
'label' => 'Show Yes/No',
'apply_filter_callback' => 'custom_product_grid::applyYesNoFilter'
]
);
- Create the applyYesNoFilter method:
In your Grid class, add this static method:
public static function applyYesNoFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $collection;
}
// Standardize inputs to 'yes' or 'no'
$standardizedValue = strtolower(trim($value));
$collection = $collection->addFieldToFilter(
'attribute_id', // Replace this with your actual attribute ID
[
'like' => "%$standardizedValue%"
]
);
return $collection;
}
- Update the column:
Now, update your column definition to use the standardized value:
$this->addColumn(
'show_yes_no',
[
'header_text' => 'Show Yes/No',
'index' => 'attribute_id', // Replace this with your actual attribute ID
'type' => 'options',
'options' => [
'no' => 'No',
'yes' => 'Yes'
],
'filter_index' => 'main_table.attribute_id',
]
);
Conclusion
By using column filters, we can standardize the input values before displaying them in our grid. This ensures that both yes and no will be displayed correctly, regardless of whether they’re entered as 0/1 or the actual string.
Remember to replace 'attribute_id' with your actual attribute ID throughout this code. You may also need to adjust the column name if it’s different from what’s shown here.
For a deeper dive into Magento grid customization, check out our comprehensive guide on Customizing Magento Product Grids at LaravelCompany.
Happy coding!