1

Is there a proper method of getting an attributes list of values (drop down list) within a template phtml file that is being called from a CMS block?

I currently have a file mytemplate.phtml and I'm calling it within a CMS block using

{{block class="Magento\Framework\View\Element\Template"  template="mytemplate.phtml"}}

mytemplate.phtml has the following code

require_once($_SERVER['DOCUMENT_ROOT'].'/app/bootstrap.php');
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();

$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

function getExistingOptions( $object_Manager,$option) {

    $eavConfig = $object_Manager->get('\Magento\Eav\Model\Config');
    $attribute = $eavConfig->getAttribute('catalog_product', $option);
    $options = $attribute->getSource()->getAllOptions();

    $optionsExists = array();

    foreach($options as $option) {
        $optionsExists[] = ["value"=>$option['value'],"label"=>$option['label']];
    }
return $optionsExists;
}

$options=array();
$options['custom_option1']=getExistingOptions($obj,"custom_option1");

After reading other peoples comments on the matter, I appreciate that I may get flogged to death for using getObjectManager, so it there a better way of doing this, or calling the loaded Magento instance from within the template file, as I cant see how else I can obtain the attribute values to display in the page?

On another note, how do i find out the attributes default selected value as this isn't given when using $attribute->getSource()->getAllOptions();?

Edit I found how to get the default value $attribute->getDefaultValue()

Your Answer

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

Browse other questions tagged or ask your own question.