Magento 2: Add unique attribute value programmaticallyCreate a sortable and filterable custom attribute to stand-alone entityGet Product Attribute Value for Dropdown Without Loading the Whole Producterror to add custom attributeswhen setup upgrade after add extention module, error occurMagento2 add custom address attributeMagento 2 add custom product attribute validation from install scriptM2.3 - Creating multiple attribute options at once generates errorConfigurable products options value - Magento 2.2.7Magento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?How to change “input file” storage location in customer account edit form

How can flights operated by the same company have such different prices when marketed by another?

Numerically Stable IIR filter

Using Python in a Bash Script

What to expect in a jazz audition

Applications of pure mathematics in operations research

Would people understand me speaking German all over Europe?

What force enables us to walk? Friction or normal reaction?

How do I respond appropriately to an overseas company that obtained a visa for me without hiring me?

Can you remove a blindfold using the Telekinesis spell?

In the Schrödinger equation, can I have a Hamiltonian without a kinetic term?

Adding a (stair/baby) gate without facing walls

Help me, I hate squares!

What is my clock telling me to do?

What is the term for completing a route uncleanly?

What Marvel character has this 'W' symbol?

GDPR Compliance - notification of data breach

Can I shorten this filter, that finds disk sizes over 100G?

Can living where Rare Earth magnetic ore is abundant provide any protection?

Planting Trees in Outer Space

NULL value causes blank row in SELECT results for text concatenation

Why is “deal 6 damage” a legit phrase?

Should I intervene when a colleague in a different department makes students run laps as part of their grade?

Can machine learning learn a function like finding maximum from a list?

How does Asimov's second law deal with contradictory orders from different people?



Magento 2: Add unique attribute value programmatically


Create a sortable and filterable custom attribute to stand-alone entityGet Product Attribute Value for Dropdown Without Loading the Whole Producterror to add custom attributeswhen setup upgrade after add extention module, error occurMagento2 add custom address attributeMagento 2 add custom product attribute validation from install scriptM2.3 - Creating multiple attribute options at once generates errorConfigurable products options value - Magento 2.2.7Magento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?How to change “input file” storage location in customer account edit form






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I'm trying to insert a value for a unique text value attribute programmatically to assign it to a product. All my others attributes have options so I can't use the same functions. If I try to insert them as an option attribute it gives an error that says "Attribute %id% doesn't work with options".



Is there a way to assign a value to this attribute and them assign it to a product?



Here is how I add a new value to an existing attribute. If value already exits, it returns the id.



/**
* Find or create a matching attribute option
*
* @param string $attributeCode Attribute the option should exist in
* @param string $label Label to find or add
* @return int
* @throws MagentoFrameworkExceptionLocalizedException
*/
public function createOrGetId($attributeCode, $label)

if (strlen($label) < 1)
throw new MagentoFrameworkExceptionLocalizedException(
__('Label for %1 must not be empty.', $attributeCode)
);


// Does it already exist?
$optionId = $this->getOptionId($attributeCode, $label);

if (!$optionId)
// If no, add it.

/** @var MagentoEavModelEntityAttributeOptionLabel $optionLabel */
$optionLabel = $this->optionLabelFactory->create();
$optionLabel->setStoreId(0);
$optionLabel->setLabel($label);

$option = $this->optionFactory->create();
$option->setLabel($optionLabel);
$option->setStoreLabels([$optionLabel]);
$option->setSortOrder(0);
$option->setIsDefault(false);

$this->attributeOptionManagement->add(
MagentoCatalogModelProduct::ENTITY,
$this->getAttribute($attributeCode)->getAttributeId(),
$option
);

// Get the inserted ID. Should be returned from the installer, but it isn't.
$optionId = $this->getOptionId($attributeCode, $label, true);


return $optionId;


/**
* Find the ID of an option matching $label, if any.
*
* @param string $attributeCode Attribute code
* @param string $label Label to find
* @param bool $force If true, will fetch the options even if they're already cached.
* @return int|false
*/
public function getOptionId($attributeCode, $label, $force = false)
!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 MagentoEavModelEntityAttributeSourceTable $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;










share|improve this question
































    1















    I'm trying to insert a value for a unique text value attribute programmatically to assign it to a product. All my others attributes have options so I can't use the same functions. If I try to insert them as an option attribute it gives an error that says "Attribute %id% doesn't work with options".



    Is there a way to assign a value to this attribute and them assign it to a product?



    Here is how I add a new value to an existing attribute. If value already exits, it returns the id.



    /**
    * Find or create a matching attribute option
    *
    * @param string $attributeCode Attribute the option should exist in
    * @param string $label Label to find or add
    * @return int
    * @throws MagentoFrameworkExceptionLocalizedException
    */
    public function createOrGetId($attributeCode, $label)

    if (strlen($label) < 1)
    throw new MagentoFrameworkExceptionLocalizedException(
    __('Label for %1 must not be empty.', $attributeCode)
    );


    // Does it already exist?
    $optionId = $this->getOptionId($attributeCode, $label);

    if (!$optionId)
    // If no, add it.

    /** @var MagentoEavModelEntityAttributeOptionLabel $optionLabel */
    $optionLabel = $this->optionLabelFactory->create();
    $optionLabel->setStoreId(0);
    $optionLabel->setLabel($label);

    $option = $this->optionFactory->create();
    $option->setLabel($optionLabel);
    $option->setStoreLabels([$optionLabel]);
    $option->setSortOrder(0);
    $option->setIsDefault(false);

    $this->attributeOptionManagement->add(
    MagentoCatalogModelProduct::ENTITY,
    $this->getAttribute($attributeCode)->getAttributeId(),
    $option
    );

    // Get the inserted ID. Should be returned from the installer, but it isn't.
    $optionId = $this->getOptionId($attributeCode, $label, true);


    return $optionId;


    /**
    * Find the ID of an option matching $label, if any.
    *
    * @param string $attributeCode Attribute code
    * @param string $label Label to find
    * @param bool $force If true, will fetch the options even if they're already cached.
    * @return int|false
    */
    public function getOptionId($attributeCode, $label, $force = false)
    !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 MagentoEavModelEntityAttributeSourceTable $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;










    share|improve this question




























      1












      1








      1


      1






      I'm trying to insert a value for a unique text value attribute programmatically to assign it to a product. All my others attributes have options so I can't use the same functions. If I try to insert them as an option attribute it gives an error that says "Attribute %id% doesn't work with options".



      Is there a way to assign a value to this attribute and them assign it to a product?



      Here is how I add a new value to an existing attribute. If value already exits, it returns the id.



      /**
      * Find or create a matching attribute option
      *
      * @param string $attributeCode Attribute the option should exist in
      * @param string $label Label to find or add
      * @return int
      * @throws MagentoFrameworkExceptionLocalizedException
      */
      public function createOrGetId($attributeCode, $label)

      if (strlen($label) < 1)
      throw new MagentoFrameworkExceptionLocalizedException(
      __('Label for %1 must not be empty.', $attributeCode)
      );


      // Does it already exist?
      $optionId = $this->getOptionId($attributeCode, $label);

      if (!$optionId)
      // If no, add it.

      /** @var MagentoEavModelEntityAttributeOptionLabel $optionLabel */
      $optionLabel = $this->optionLabelFactory->create();
      $optionLabel->setStoreId(0);
      $optionLabel->setLabel($label);

      $option = $this->optionFactory->create();
      $option->setLabel($optionLabel);
      $option->setStoreLabels([$optionLabel]);
      $option->setSortOrder(0);
      $option->setIsDefault(false);

      $this->attributeOptionManagement->add(
      MagentoCatalogModelProduct::ENTITY,
      $this->getAttribute($attributeCode)->getAttributeId(),
      $option
      );

      // Get the inserted ID. Should be returned from the installer, but it isn't.
      $optionId = $this->getOptionId($attributeCode, $label, true);


      return $optionId;


      /**
      * Find the ID of an option matching $label, if any.
      *
      * @param string $attributeCode Attribute code
      * @param string $label Label to find
      * @param bool $force If true, will fetch the options even if they're already cached.
      * @return int|false
      */
      public function getOptionId($attributeCode, $label, $force = false)
      !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 MagentoEavModelEntityAttributeSourceTable $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;










      share|improve this question
















      I'm trying to insert a value for a unique text value attribute programmatically to assign it to a product. All my others attributes have options so I can't use the same functions. If I try to insert them as an option attribute it gives an error that says "Attribute %id% doesn't work with options".



      Is there a way to assign a value to this attribute and them assign it to a product?



      Here is how I add a new value to an existing attribute. If value already exits, it returns the id.



      /**
      * Find or create a matching attribute option
      *
      * @param string $attributeCode Attribute the option should exist in
      * @param string $label Label to find or add
      * @return int
      * @throws MagentoFrameworkExceptionLocalizedException
      */
      public function createOrGetId($attributeCode, $label)

      if (strlen($label) < 1)
      throw new MagentoFrameworkExceptionLocalizedException(
      __('Label for %1 must not be empty.', $attributeCode)
      );


      // Does it already exist?
      $optionId = $this->getOptionId($attributeCode, $label);

      if (!$optionId)
      // If no, add it.

      /** @var MagentoEavModelEntityAttributeOptionLabel $optionLabel */
      $optionLabel = $this->optionLabelFactory->create();
      $optionLabel->setStoreId(0);
      $optionLabel->setLabel($label);

      $option = $this->optionFactory->create();
      $option->setLabel($optionLabel);
      $option->setStoreLabels([$optionLabel]);
      $option->setSortOrder(0);
      $option->setIsDefault(false);

      $this->attributeOptionManagement->add(
      MagentoCatalogModelProduct::ENTITY,
      $this->getAttribute($attributeCode)->getAttributeId(),
      $option
      );

      // Get the inserted ID. Should be returned from the installer, but it isn't.
      $optionId = $this->getOptionId($attributeCode, $label, true);


      return $optionId;


      /**
      * Find the ID of an option matching $label, if any.
      *
      * @param string $attributeCode Attribute code
      * @param string $label Label to find
      * @param bool $force If true, will fetch the options even if they're already cached.
      * @return int|false
      */
      public function getOptionId($attributeCode, $label, $force = false)
      !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 MagentoEavModelEntityAttributeSourceTable $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;







      magento2 product attributes product-attribute custom-attributes






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 22 at 13:39









      Kirti Nariya

      1,7785 silver badges19 bronze badges




      1,7785 silver badges19 bronze badges










      asked Apr 26 '18 at 16:18









      Rubén MRubén M

      62 bronze badges




      62 bronze badges























          0






          active

          oldest

          votes














          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "479"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f223892%2fmagento-2-add-unique-attribute-value-programmatically%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Magento Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f223892%2fmagento-2-add-unique-attribute-value-programmatically%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

          Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

          Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form