Magento 2 - Comment obtenir la valeur des options d'attribut de l'entité eav?


18

Comment puis-je obtenir les valeurs des options d'attribut de l'entité eav?
J'ai trouvé une solution uniquement pour magento 1.x mais M2 je ne sais pas.
M1:

$attr = Mage::getResourceModel('eav/entity_attribute_collection')->setCodeFilter('specialty')->getData()[0];
$attributeModel = Mage::getModel('eav/entity_attribute')->load($attr['attribute_id']);
$src =  $attributeModel->getSource()->getAllOptions();

Quelqu'un sait, montrez-moi étape par étape, merci! Merci!

Réponses:


55

vous pouvez ajouter au constructeur de votre classe une instance \Magento\Eav\Model\Configcomme celle-ci:

protected $eavConfig;
public function __construct(
    ...
    \Magento\Eav\Model\Config $eavConfig,
    ...
){
    ...
    $this->eavConfig = $eavConfig;
    ...
}

alors vous pouvez l'utiliser dans votre classe

$attribute = $this->eavConfig->getAttribute('catalog_product', 'attribute_code_here');
$options = $attribute->getSource()->getAllOptions();

Comment obtenir "valeur" et "label"?
MrTo-Kane

1
voyez à quoi ressemble le résultat. Var le vider ou quelque chose.
Marius

array (2) {[0] => array (2) {["value"] => int (1) ["label"] => objet (Magento \ Framework \ Phrase) # 1504 (2) {["text ":" Magento \ Framework \ Phrase ": privé] => chaîne (7)" Activé "[" arguments ":" Magento \ Framework \ Phrase ": privé] => tableau (0) {}}} [1] = > array (2) {["value"] => int (2) ["label"] => objet (Magento \ Framework \ Phrase) # 1494 (2) {["text": "Magento \ Framework \ Phrase" : private] => string (8) "Disabled" ["arguments": "Magento \ Framework \ Phrase": private] => array (0) {}}}}
MrTo-Kane

12
Petite mais importante remarque: si disponible, mieux vaut utiliser Module Service Layer. Pour les attributs eav c'est \Magento\Eav\Api\Attribute RepositoryInterface. Tout ce qui n'est pas marqué comme @api est traité comme privé et peut être supprimé dans les versions mineures.
KAndy

5
@KAndy Bonne remarque. Vous pouvez écrire cela comme réponse. Je pense que c'est bien mieux que le mien.
Marius

5

Vous pouvez le faire en appelant simplement le code ci-dessous dans votre fichier Block.

<?php
namespace Vendor\Package\Block;

class Blockname extends \Magento\Framework\View\Element\Template
{
    protected $_productAttributeRepository;

    public function __construct(        
        \Magento\Framework\View\Element\Template\Context $context,   
        \Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository,
        array $data = [] 
    ){        
        parent::__construct($context,$data);
        $this->_productAttributeRepository = $productAttributeRepository;
    } 

    public function getAllBrand(){
        $manufacturerOptions = $this->_productAttributeRepository->get('manufacturer')->getOptions();       
        $values = array();
        foreach ($manufacturerOptions as $manufacturerOption) { 
           //$manufacturerOption->getValue();  // Value
            $values[] = $manufacturerOption->getLabel();  // Label
        }
        return $values;
    }  
}

Appelez à l'intérieur de votre fichier phtml,

<div class="manufacturer-name">
      <?php $getOptionValue = $this->getAllBrand();?>
      <?php foreach($getOptionValue as $value){ ?>
           <span><?php echo $value;?></span>
      <?php } ?>
</div>

Merci.


Cela ne renvoie pas les options des attributs configurés pour utiliser des swatchentrées, comme color. La getOptions()méthode est codée en dur pour certains types d'entrée, comme les "listes déroulantes", de sorte qu'elle ignore les options d'entrée de nuance. Juste un avertissement si quelqu'un d'autre se présente à cela.
thaddeusmt

Salut @Rakesh, Comment j'y parviens, mais pour l'administrateur. J'ai besoin de ces valeurs d'option pour le filtre de colonne de grille. Peux-tu me dire s'il te plait.
Ravi Soni

5

Utilisez le code suivant pour obtenir toutes les options d'attribut.

function getExistingOptions( $object_Manager ) {

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

$optionsExists = array();

foreach($options as $option) {
    $optionsExists[] = $option['label'];
}

return $optionsExists;

 }

Pouvez-vous cliquer ici pour des explications plus détaillées. http://www.pearlbells.co.uk/code-snippets/get-magento-attribute-options-programmatically/


4

J'utilise la couche de service Api Magento\Eav\Api\AttributeRepositoryInterfacesuggérée par @kandy dans les commentaires sur la réponse @marius.

Injectez le membre de données de service dans votre constructeur comme suit.

protected $eavAttributeRepository;
public function __construct(
    ...
    \Magento\Eav\Api\AttributeRepositoryInterface $eavAttributeRepositoryInterface,
    ...
){
    ...
    $this->eavAttributeRepository = $eavAttributeRepositoryInterface;
    ...
}

Et vous pouvez obtenir l'attribut en utilisant ceci.

$attribute = $this->eavAttributeRepository->get(
    \Magento\Catalog\Model\Product::ENTITY,
    'attribute_code_here'
);
// var_dump($attribute->getData()); 

Afin d'obtenir le tableau de valeurs d'options d'attribut, utilisez ceci.

$options = $attribute->getSource()->getAllOptions();

2

Injectez une instance de \Magento\Catalog\Model\Product\Attribute\Repositorydans votre constructeur (dans un bloc, une classe d'assistance ou n'importe où):

/**
 * @var \Magento\Catalog\Model\Product\Attribute\Repository $_productAttributeRepository
 */
protected $_productAttributeRepository;

/**
 * ...
 * @param \Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository
 * ...
 */
public function __construct(
    ...
    \Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository,
    ...
) {
    ...
    $this->_productAttributeRepository = $productAttributeRepository;
    ...
}

Créez ensuite une méthode dans votre classe pour obtenir l'attribut par code:

/**
 * Get single product attribute data 
 *
 * @return Magento\Catalog\Api\Data\ProductAttributeInterface
 */
public function getProductAttributeByCode($code)
{
    $attribute = $this->_productAttributeRepository->get($code);
    return $attribute;
}

Vous pouvez ensuite appeler cette méthode comme ceci, par exemple à l'intérieur d'un fichier .phtml

$attrTest = $block->getProductAttributeByCode('test');

Ensuite, vous pouvez effectuer des appels sur l'objet attribut, par exemple

  1. Obtenez les options: $attribute->getOptions()
  2. Obtenez une étiquette frontale pour chaque magasin: $attrTest->getFrontendLabels()
  3. Déboguez le tableau de données: echo '> ' . print_r($attrTest->debug(), true);

debug: Array ([attribute_id] => 274 [entity_type_id] => 4 [attribute_code] => product_manual_download_label [backend_type] => varchar [frontend_input] => text [frontend_label] => Étiquette de téléchargement du manuel du produit [is_required] => 0 [ is_user_defined] => 1 [default_value] => Téléchargement du manuel du produit [is_unique] => 0 [is_global] => 0 [is_visible] => 1 [is_searchable] => 0 [is_filterable] => 0 [is_comparable] => 0 [ is_visible_on_front] => 0 [is_html_allowed_on_front] => 1 [is_used_for_price_rules] => 0 [is_filterable_in_search] => 0 [used_in_product_listing] => 0 [used_for_sort_by] => 0 [is_visible_in_earch_ =>>0 [is_wysiwyg_enabled] => 0 [is_used_for_promo_rules] => 0 [is_required_in_admin_store] => 0 [is_used_in_grid] => 1 [is_visible_in_grid] => 1 [is_filterable_in_grid] => 1 [is_filterable_in_grid] => 1 [search_weight]


1
Ceci est une réponse très bien expliquée
domdambrogia

0
   <?php
      /* to load the Product */
  $_product = $block->getProduct();
  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $attributeSet = $objectManager- 
   >create('Magento\Eav\Api\AttributeSetRepositoryInterface');
  $attributeSetRepository = $attributeSet->get($_product->getAttributeSetId());
  $_attributeValue  = $attributeSetRepository->getAttributeSetName();  
En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.