Пример #1
0
 /**
  * Save attribute options just created by user
  *
  * @return void
  * @TODO Move this logic to configurable product type model
  *   when full set of operations for attribute options during
  *   product creation will be implemented: edit labels, remove, reorder.
  * Currently only addition of options to end and removal of just added option is supported.
  */
 protected function _saveAttributeOptions()
 {
     $productData = (array) $this->getRequest()->getParam('product');
     if (!isset($productData['configurable_attributes_data'])) {
         return;
     }
     foreach ($productData['configurable_attributes_data'] as &$attributeData) {
         $values = array();
         foreach ($attributeData['values'] as $valueId => $priceData) {
             if (isset($priceData['label'])) {
                 $attribute = $this->attributeFactory->create();
                 $attribute->load($attributeData['attribute_id']);
                 $optionsBefore = $attribute->getSource()->getAllOptions(false);
                 $attribute->setOption(array('value' => array('option_0' => array($priceData['label'])), 'order' => array('option_0' => count($optionsBefore) + 1)));
                 $attribute->save();
                 $attribute = $this->attributeFactory->create();
                 $attribute->load($attributeData['attribute_id']);
                 $optionsAfter = $attribute->getSource()->getAllOptions(false);
                 $newOption = array_pop($optionsAfter);
                 unset($priceData['label']);
                 $valueId = $newOption['value'];
                 $priceData['value_index'] = $valueId;
             }
             $values[$valueId] = $priceData;
         }
         $attributeData['values'] = $values;
     }
     $this->getRequest()->setParam('product', $productData);
 }
Пример #2
0
 /**
  * Check whether Msrp applied to product Product Type
  *
  * @param \Magento\Catalog\Model\Product $product
  * @return bool
  */
 public function canApplyToProduct($product)
 {
     if ($this->mapApplyToProductType === null) {
         /** @var $attribute \Magento\Catalog\Model\Resource\Eav\Attribute */
         $attribute = $this->eavAttributeFactory->create()->loadByCode(Product::ENTITY, 'msrp');
         $this->mapApplyToProductType = $attribute->getApplyTo();
     }
     return in_array($product->getTypeId(), $this->mapApplyToProductType);
 }
Пример #3
0
 /**
  * {@inheritdoc}
  */
 public function update($id, AttributeMetadata $attribute)
 {
     /** @var \Magento\Catalog\Model\Resource\Eav\Attribute $attributeModel */
     $model = $this->attributeFactory->create();
     $model->loadByCode(\Magento\Catalog\Model\Product::ENTITY, $id);
     if (!$model->getId()) {
         throw NoSuchEntityException::singleField(AttributeMetadata::ATTRIBUTE_CODE, $id);
     }
     $data = $attribute->__toArray();
     // this fields should not be changed
     $data[AttributeMetadata::ATTRIBUTE_ID] = $model->getAttributeId();
     $data[AttributeMetadata::USER_DEFINED] = $model->getIsUserDefined();
     $data[AttributeMetadata::FRONTEND_INPUT] = $model->getFrontendInput();
     if (isset($data[AttributeMetadata::FRONTEND_LABEL]) && is_array($data[AttributeMetadata::FRONTEND_LABEL])) {
         $frontendLabel[0] = $model->getFrontendLabel();
         foreach ($data[AttributeMetadata::FRONTEND_LABEL] as $item) {
             if (isset($item[FrontendLabel::STORE_ID], $item[FrontendLabel::LABEL])) {
                 $frontendLabel[$item[FrontendLabel::STORE_ID]] = $item[FrontendLabel::LABEL];
             }
         }
         $data[AttributeMetadata::FRONTEND_LABEL] = $frontendLabel;
     }
     if (!$model->getIsUserDefined()) {
         // Unset attribute field for system attributes
         unset($data[AttributeMetadata::APPLY_TO]);
     }
     try {
         $model->addData($data);
         $model->save();
     } catch (\Exception $e) {
         throw new CouldNotSaveException('Could not update product attribute' . $e->getMessage());
     }
     return $model->getAttributeCode();
 }
Пример #4
0
 /**
  * Save attribute options just created by user
  *
  * @return array
  * @TODO Move this logic to configurable product type model
  *   when full set of operations for attribute options during
  *   product creation will be implemented: edit labels, remove, reorder.
  * Currently only addition of options to end and removal of just added option is supported.
  */
 protected function saveAttributeOptions()
 {
     $options = (array) $this->getRequest()->getParam('options');
     $savedOptions = [];
     foreach ($options as $option) {
         if (isset($option['label']) && isset($option['is_new'])) {
             $attribute = $this->attributeFactory->create();
             $attribute->load($option['attribute_id']);
             $optionsBefore = $attribute->getSource()->getAllOptions(false);
             $attribute->setOption(['value' => ['option_0' => [$option['label']]], 'order' => ['option_0' => count($optionsBefore) + 1]]);
             $attribute->save();
             $attribute = $this->attributeFactory->create();
             $attribute->load($option['attribute_id']);
             $optionsAfter = $attribute->getSource()->getAllOptions(false);
             $newOption = array_pop($optionsAfter);
             $savedOptions[$option['id']] = $newOption['value'];
         }
     }
     return $savedOptions;
 }
Пример #5
0
 /**
  * Retrieve codes of indexable attributes from given attribute set
  *
  * @param \Magento\Eav\Model\Entity\Attribute\Set $set
  * @return array
  */
 public function filter(\Magento\Eav\Model\Entity\Attribute\Set $set)
 {
     $codes = [];
     $catalogResource = $this->_attributeFactory->create();
     foreach ($set->getGroups() as $group) {
         /** @var $group \Magento\Eav\Model\Entity\Attribute\Group */
         foreach ($group->getAttributes() as $attribute) {
             /** @var $attribute \Magento\Eav\Model\Entity\Attribute */
             $catalogResource->load($attribute->getId());
             if ($catalogResource->isIndexable()) {
                 // Attribute requires to be cloned for new dataset to maintain attribute set changes
                 $attributeClone = clone $attribute;
                 $attributeClone->load($attribute->getAttributeId());
                 $codes[] = $attributeClone->getAttributeCode();
                 unset($attributeClone);
             }
         }
     }
     return $codes;
 }
Пример #6
0
 /**
  * {@inheritdoc}
  */
 public function run()
 {
     $this->logger->log('Installing catalog attributes:');
     $attributeCount = 0;
     foreach ($this->moduleList->getNames() as $moduleName) {
         $fileName = substr($moduleName, strpos($moduleName, "_") + 1) . '/attributes.csv';
         $fileName = $this->fixtureHelper->getPath($fileName);
         if (!$fileName) {
             continue;
         }
         $csvReader = $this->csvReaderFactory->create(['fileName' => $fileName, 'mode' => 'r']);
         foreach ($csvReader as $data) {
             $data['attribute_set'] = explode("\n", $data['attribute_set']);
             /** @var \Magento\Catalog\Model\Resource\Eav\Attribute $attribute */
             $attribute = $this->eavConfig->getAttribute('catalog_product', $data['attribute_code']);
             if (!$attribute) {
                 $attribute = $this->attributeFactory->create();
             }
             $frontendLabel = explode("\n", $data['frontend_label']);
             if (count($frontendLabel) > 1) {
                 $data['frontend_label'] = [];
                 $data['frontend_label'][\Magento\Store\Model\Store::DEFAULT_STORE_ID] = $frontendLabel[0];
                 $data['frontend_label'][$this->storeManager->getStoreId()] = $frontendLabel[1];
             }
             $data['option'] = $this->getOption($attribute, $data);
             $data['source_model'] = $this->productHelper->getAttributeSourceModelByInputType($data['frontend_input']);
             $data['backend_model'] = $this->productHelper->getAttributeBackendModelByInputType($data['frontend_input']);
             $data += ['is_filterable' => 0, 'is_filterable_in_search' => 0, 'apply_to' => []];
             $data['backend_type'] = $attribute->getBackendTypeByInput($data['frontend_input']);
             $attribute->addData($data);
             $attribute->setIsUserDefined(1);
             $attribute->setEntityTypeId($this->getEntityTypeId());
             $attribute->save();
             $attributeId = $attribute->getId();
             if (is_array($data['attribute_set'])) {
                 foreach ($data['attribute_set'] as $setName) {
                     $setName = trim($setName);
                     $attributeCount++;
                     $attributeSet = $this->processAttributeSet($setName);
                     $attributeGroupId = $attributeSet->getDefaultGroupId();
                     $attribute = $this->attributeFactory->create();
                     $attribute->setId($attributeId)->setAttributeGroupId($attributeGroupId)->setAttributeSetId($attributeSet->getId())->setEntityTypeId($this->getEntityTypeId())->setSortOrder($attributeCount + 999)->save();
                 }
             }
             $this->logger->logInline('.');
         }
     }
     $this->eavConfig->clear();
 }
Пример #7
0
 /**
  * {@inheritdoc}
  */
 public function getList($productSku)
 {
     $result = array();
     /** @var \Magento\Catalog\Model\Product $product */
     $product = $this->productRepository->get($productSku);
     $galleryAttribute = $this->attributeFactory->create()->loadByCode($this->eavConfig->getEntityType(\Magento\Catalog\Model\Product::ENTITY), 'media_gallery');
     $container = new \Magento\Framework\Object(array('attribute' => $galleryAttribute));
     $gallery = $this->mediaGallery->loadGallery($product, $container);
     $productImages = $this->getMediaAttributeValues($product);
     foreach ($gallery as $image) {
         $this->galleryEntryBuilder->setId($image['value_id']);
         $this->galleryEntryBuilder->setLabel($image['label_default']);
         $this->galleryEntryBuilder->setTypes(array_keys($productImages, $image['file']));
         $this->galleryEntryBuilder->setDisabled($image['disabled_default']);
         $this->galleryEntryBuilder->setPosition($image['position_default']);
         $this->galleryEntryBuilder->setFile($image['file']);
         $result[] = $this->galleryEntryBuilder->create();
     }
     return $result;
 }
Пример #8
0
 /**
  * Retrieve product attribute by identifier
  * Difference from abstract: any attribute is available, not just the ones from $product's attribute set
  *
  * @param  int $attributeId
  * @param  \Magento\Catalog\Model\Product $product
  * @return \Magento\Catalog\Model\Resource\Eav\Attribute
  */
 public function getAttributeById($attributeId, $product)
 {
     $attribute = parent::getAttributeById($attributeId, $product);
     return $attribute ?: $this->_eavAttributeFactory->create()->load($attributeId);
 }
Пример #9
0
 /**
  * @return \Magento\Backend\Model\View\Result\Redirect
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function execute()
 {
     $data = $this->getRequest()->getPostValue();
     $resultRedirect = $this->resultRedirectFactory->create();
     if ($data) {
         $setId = $this->getRequest()->getParam('set');
         $attributeSet = null;
         if (!empty($data['new_attribute_set_name'])) {
             $name = $this->filterManager->stripTags($data['new_attribute_set_name']);
             $name = trim($name);
             try {
                 /** @var $attributeSet \Magento\Eav\Model\Entity\Attribute\Set */
                 $attributeSet = $this->buildFactory->create()->setEntityTypeId($this->_entityTypeId)->setSkeletonId($setId)->setName($name)->getAttributeSet();
             } catch (AlreadyExistsException $alreadyExists) {
                 $this->messageManager->addError(__('An attribute set named \'%1\' already exists.', $name));
                 $this->messageManager->setAttributeData($data);
                 return $resultRedirect->setPath('catalog/*/edit', ['_current' => true]);
             } catch (\Magento\Framework\Exception\LocalizedException $e) {
                 $this->messageManager->addError($e->getMessage());
             } catch (\Exception $e) {
                 $this->messageManager->addException($e, __('Something went wrong while saving the attribute.'));
             }
         }
         $redirectBack = $this->getRequest()->getParam('back', false);
         /* @var $model \Magento\Catalog\Model\Resource\Eav\Attribute */
         $model = $this->attributeFactory->create();
         $attributeId = $this->getRequest()->getParam('attribute_id');
         $attributeCode = $this->getRequest()->getParam('attribute_code');
         $frontendLabel = $this->getRequest()->getParam('frontend_label');
         $attributeCode = $attributeCode ?: $this->generateCode($frontendLabel[0]);
         if (strlen($this->getRequest()->getParam('attribute_code')) > 0) {
             $validatorAttrCode = new \Zend_Validate_Regex(['pattern' => '/^[a-z][a-z_0-9]{0,30}$/']);
             if (!$validatorAttrCode->isValid($attributeCode)) {
                 $this->messageManager->addError(__('Attribute code "%1" is invalid. Please use only letters (a-z), ' . 'numbers (0-9) or underscore(_) in this field, first character should be a letter.', $attributeCode));
                 return $resultRedirect->setPath('catalog/*/edit', ['attribute_id' => $attributeId, '_current' => true]);
             }
         }
         $data['attribute_code'] = $attributeCode;
         //validate frontend_input
         if (isset($data['frontend_input'])) {
             /** @var $inputType \Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype\Validator */
             $inputType = $this->validatorFactory->create();
             if (!$inputType->isValid($data['frontend_input'])) {
                 foreach ($inputType->getMessages() as $message) {
                     $this->messageManager->addError($message);
                 }
                 return $resultRedirect->setPath('catalog/*/edit', ['attribute_id' => $attributeId, '_current' => true]);
             }
         }
         if ($attributeId) {
             $model->load($attributeId);
             if (!$model->getId()) {
                 $this->messageManager->addError(__('This attribute no longer exists.'));
                 return $resultRedirect->setPath('catalog/*/');
             }
             // entity type check
             if ($model->getEntityTypeId() != $this->_entityTypeId) {
                 $this->messageManager->addError(__('We can\'t update the attribute.'));
                 $this->_session->setAttributeData($data);
                 return $resultRedirect->setPath('catalog/*/');
             }
             $data['attribute_code'] = $model->getAttributeCode();
             $data['is_user_defined'] = $model->getIsUserDefined();
             $data['frontend_input'] = $model->getFrontendInput();
         } else {
             /**
              * @todo add to helper and specify all relations for properties
              */
             $data['source_model'] = $this->productHelper->getAttributeSourceModelByInputType($data['frontend_input']);
             $data['backend_model'] = $this->productHelper->getAttributeBackendModelByInputType($data['frontend_input']);
         }
         $data += ['is_filterable' => 0, 'is_filterable_in_search' => 0, 'apply_to' => []];
         if (is_null($model->getIsUserDefined()) || $model->getIsUserDefined() != 0) {
             $data['backend_type'] = $model->getBackendTypeByInput($data['frontend_input']);
         }
         $defaultValueField = $model->getDefaultValueByInput($data['frontend_input']);
         if ($defaultValueField) {
             $data['default_value'] = $this->getRequest()->getParam($defaultValueField);
         }
         if (!$model->getIsUserDefined() && $model->getId()) {
             // Unset attribute field for system attributes
             unset($data['apply_to']);
         }
         $model->addData($data);
         if (!$attributeId) {
             $model->setEntityTypeId($this->_entityTypeId);
             $model->setIsUserDefined(1);
         }
         $groupCode = $this->getRequest()->getParam('group');
         if ($setId && $groupCode) {
             // For creating product attribute on product page we need specify attribute set and group
             $attributeSetId = $attributeSet ? $attributeSet->getId() : $setId;
             $groupCollection = $attributeSet ? $attributeSet->getGroups() : $this->groupCollectionFactory->create()->setAttributeSetFilter($attributeSetId)->load();
             foreach ($groupCollection as $group) {
                 if ($group->getAttributeGroupCode() == $groupCode) {
                     $attributeGroupId = $group->getAttributeGroupId();
                     break;
                 }
             }
             $model->setAttributeSetId($attributeSetId);
             $model->setAttributeGroupId($attributeGroupId);
         }
         try {
             $model->save();
             $this->messageManager->addSuccess(__('You saved the product attribute.'));
             $this->_attributeLabelCache->clean();
             $this->_session->setAttributeData(false);
             if ($this->getRequest()->getParam('popup')) {
                 $requestParams = ['attributeId' => $this->getRequest()->getParam('product'), 'attribute' => $model->getId(), '_current' => true, 'product_tab' => $this->getRequest()->getParam('product_tab')];
                 if (!is_null($attributeSet)) {
                     $requestParams['new_attribute_set_id'] = $attributeSet->getId();
                 }
                 $resultRedirect->setPath('catalog/product/addAttribute', $requestParams);
             } elseif ($redirectBack) {
                 $resultRedirect->setPath('catalog/*/edit', ['attribute_id' => $model->getId(), '_current' => true]);
             } else {
                 $resultRedirect->setPath('catalog/*/');
             }
             return $resultRedirect;
         } catch (\Exception $e) {
             $this->messageManager->addError($e->getMessage());
             $this->_session->setAttributeData($data);
             return $resultRedirect->setPath('catalog/*/edit', ['attribute_id' => $attributeId, '_current' => true]);
         }
     }
     return $resultRedirect->setPath('catalog/*/');
 }
Пример #10
0
 /**
  * Creates eav attribute resource model
  *
  * @param array $data
  * @return \Magento\Catalog\Model\Resource\Eav\Attribute
  */
 public function createEavAttributeResource($data = array())
 {
     return $this->_eavAttributeResourceFactory->create($data);
 }