3

I have a custom Product options dropdown attribute and i want to add or update the label option based on the store id and default label, for example, I have a data like this:

$attribute_code = 'impression';
$default_label = 'Love';
$label = 'Liebe';
$storeId = '2';

First i need to get the default attribute code option id by the label, which i have successfully done like this:

public function getOptionId($attributeCode, $label, $force = false){

    /** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
    $attribute = $this->getAttribute($attributeCode);
    $id = $attribute->getSource()->getOptionId($label);
    if (!empty($id)) {
      return $id;
    } else return false;

    // Build option array if necessary
    if ($force === true || !isset($this->attributeValues[ $attribute->getAttributeId() ])) {
        $this->attributeValues[ $attribute->getAttributeId() ] = [];

        // We have to generate a new sourceModel instance each time through to prevent it from
        // referencing its _options cache. No other way to get it to pick up newly-added values.

        /** @var \Magento\Eav\Model\Entity\Attribute\Source\Table $sourceModel */
        $sourceModel = $this->tableFactory->create();
        $sourceModel->setAttribute($attribute);

        foreach ($sourceModel->getAllOptions() as $option) {
            $this->attributeValues[ $attribute->getAttributeId() ][ $option['label'] ] = $option['value'];
        }
    }

    // Return option ID if exists
    if (isset($this->attributeValues[ $attribute->getAttributeId() ][ $label ])) {
        return $this->attributeValues[ $attribute->getAttributeId() ][ $label ];
    }

    // Return false if does not exist
    return false;
}

Then i need to add the check if the label already exists based on store id and if not add the label that referenced to the option id, if exists then update it, for this part i have no idea how to do it??

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.