Magento 2 - How to know all valid attributes to use in addAttributeToSelect?
-
14-04-2021 - |
Question
I often see code like this where the developer just inserts *
into addAttributeToSelect("*")
instead of selecting only the necessary attributes.
public function toOptionArray()
{
$optionArray = [];
$arr = $this->collectionFactory->create()->addAttributeToSelect("*");
foreach ($arr as $key => $value) {
$optionArray[] = [
'value' => $value->getId(),
'label' => $value->getName(),
];
}
return $optionArray;
}
As you can see, only the attributes id
and name
are getting used, so the developer should configure addAttributeToSelect accordingly for better performance.
So I tried to improve the code by using this addAttributeToSelect("id, name");
but now the name is not available in the data anymore, because name does not seem to be the right column identifier.
How do I know all valid available attributes which I can use?
I looked up the database table catalog_category_entity
and catalog_category_product
but they do not even contain a column with name "id" and there is no information about the category name.
I also tried to output an element from $arr
to see if it contains interesting information:
public function toOptionArray()
{
$optionArray = [];
$arr = $this->collectionFactory->create()->addAttributeToSelect("*");
// Debug ------------------------------------------
echo "<pre>";
print_r($arr[0]);
echo "</pre>";
exit();
// ------------------------------------------------
foreach ($arr as $key => $value) {
$optionArray[] = [
'value' => $value->getId(),
'label' => $value->getName(),
];
}
return $optionArray;
}
But I get
"Error: Cannot use object of type Magento\Catalog\Model\ResourceModel\Category\Collection as array in /home/x/y/app/code/Company/Shipping/Model/Source/Category.php:30"
... even though the same $arr
is later used in the foreach with no problem, so the error makes no sense.
Solution
this function has a lot of abstraction/parsing and use of config files to decide on the fields to bring. Nowadays, we can also alter functions with plugins; meaning even if we come up with a rule to describe the fields to expect, essentially, they are liable to be changed by many parameters.
However, if you put the symbol *, you will see all the fields available in your query without any clever theory behind.
However, to retrieve a list of specific fields, you might want to use a list of fields as an array like my example below.
I put a few screenshots showing you on my PHPSTORM install how it looks and what does you can read:
$collection->addFieldToSelect('*');
gives the response below:
`$collection->addFieldToSelect(['small_image', 'name']);` gives the response below: