Question

I have Magento 2.3. I created Status.php in [Banner/Slider/Model/Slider/Source] but it gives an error [Invalid argument supplied for foreach() in C:\xampp\htdocs\mag3\app\code\Banner\Slider\Model\Slider\Source\Status.php on line 22]

this is Status.php

<?php

namespace Banner\Slider\Model\Slider\Source;

use Banner\Slider\Model\Slider;
use Magento\Framework\Data\OptionSourceInterface;


class Status implements OptionSourceInterface
{
    protected $status_slider;

    public function __construct(Slider $status_slider)
    {
        $this->status_slider = $status_slider;
    }

    public function toOptionArray()
    {
        $availableOptions = $this->status_slider->getAvailableStatuses();
        $options = [];
        foreach ($availableOptions as $key => $value) {
            $options[] = [
                'label' => $value,
                'value' => $key,
            ];
        }
        return $options;
    }
}
Was it helpful?

Solution

I modified your function toOptionArray() for following things..

  1. To understand the type of that variable $availableOptions
  2. To find if $availableOptions is null, then we are trying to bypass the foreach loop.. it will not display the error but problem is in previous steps may be in calling function getAvailableStatuses(); you need to backtrace more.
  3. I swap the key and value part inside foreach loop as i think the value must come in front of value. You can also try that.. Please read all comments carefully.
public function toOptionArray()
    {
        $availableOptions = $this->status_slider->getAvailableStatuses();
        echo gettype($availableOptions);//to find the type of $availableOptions
        $options = [];
        if(isset($availableOptions))//this can only be used to avoid error, please 
        {//try after commenting this if block... only starting and ending of if  
         //and its curly brackts but not the foreach loop
        foreach ($availableOptions as $key => $value) {
            $options[] = [
                'label' => $key,
                'value' => $value,//I reversed key and value here 
            ];
           }
        }//you can comment if block then remove comment to check.. 
        return $options;
    }

Please let me know in comments if you need any more clarification. I hope it will solve your problem.
Thanks
Vibhore

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top