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.