0

I am trying to test magento 2.4 with PHP7.4.

I have a custom module with this code:

//checking for absolute weight
$res = $this->_objectManager->get('Magento\Framework\App\ResourceConnection');
$con = $res->getConnection('read');
$row = $con->fetchRow("select `absolute_weight`, `absolute_sku`, `sku_order` from {$res->getTableName('dynamicproductoptions_options')} where `product_id`={$product->getId()} and (`store_id`={$product->getStoreId()} or `store_id`=0) order by `store_id` desc");
$isAbsoluteWeight = (int) $row['absolute_weight'];
$isAbsoluteSku = (int) $row['absolute_sku'];

But this line:

$isAbsoluteWeight = (int) $row['absolute_weight'];

return error when I try to add a product in cart:

Notice: Trying to access array offset on value of type bool in my file.php

How can I fix it the right way please?

3

Notice: Trying to access array offset on value of type bool in my file.php

This means $row is false, your query returned no results. You need to at least add in if statements for the case where the query returns no results. More accurately you need to check if these array offsets exist when using them. An Example based on your code:

//checking for absolute weight
$res = $this->_objectManager->get('Magento\Framework\App\ResourceConnection');
$con = $res->getConnection('read');
$row = $con->fetchRow("select `absolute_weight`, `absolute_sku`, `sku_order` from {$res->getTableName('dynamicproductoptions_options')} where `product_id`={$product->getId()} and (`store_id`={$product->getStoreId()} or `store_id`=0) order by `store_id` desc");
$isAbsoluteWeight = null;
$isAbsoluteSku = null;
if (!empty($row)) {
    $isAbsoluteWeight = !empty($row['absolute_weight']) ? (int) $row['absolute_weight'] : false;
    $isAbsoluteSku = !empty($row['absolute_sku']) ? (int) $row['absolute_sku'] : false;
}

Then what you attempt to process those values you need to add the conditionals necessary to prevent the errors.

if ($isAbsoluteWeight && $isAbsoluteSku) {
    //Do stuff
}
2
  • Its a very bad idea to use the object manager and it should be avoided. So i would not recommend this solutions as you will encounter issues in the future. – Petar Borisovski Oct 2 '20 at 14:26
  • The answer is very clear that it is limiting the response to using the existing code in the question and giving the minimum necessary changes. This includes the object manager. But while you are technically correct the object manager should not be used in this way, the solution focus' on sanity checking all unknown information before use. – Mark Rees Oct 2 '20 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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