Example #1
1
 /**
  * Check whether Msrp applied to product Product Type
  *
  * @param \Magento\Catalog\Model\Product $product
  * @return bool
  * @api
  */
 public function canApplyToProduct($product)
 {
     if ($this->mapApplyToProductType === null) {
         /** @var $attribute \Magento\Catalog\Model\ResourceModel\Eav\Attribute */
         $attribute = $this->eavAttributeFactory->create()->loadByCode(Product::ENTITY, 'msrp');
         $this->mapApplyToProductType = $attribute->getApplyTo();
     }
     return in_array($product->getTypeId(), $this->mapApplyToProductType);
 }
 /**
  * Modification of attribute config
  *
  * @param string $attributeCode
  * @param array $attributeConfig
  * @return array
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 protected function modifyAttributeConfig($attributeCode, array $attributeConfig)
 {
     /** @var Product $product */
     $product = $this->locator->getProduct();
     /** @var EavAttribute $eavAttribute */
     $eavAttribute = $this->eavAttributeFactory->create()->loadByCode(Product::ENTITY, $attributeCode);
     return array_replace_recursive($attributeConfig, ['arguments' => ['data' => ['config' => ['componentType' => 'dynamicRows', 'formElement' => 'component', 'renderDefaultRecord' => false, 'itemTemplate' => 'record', 'dataScope' => '', 'dndConfig' => ['enabled' => false]]]], 'children' => ['record' => ['arguments' => ['data' => ['config' => ['componentType' => Container::NAME, 'isTemplate' => true, 'is_collection' => true, 'component' => 'Magento_Ui/js/dynamic-rows/record', 'dataScope' => '']]], 'children' => ['countryState' => ['arguments' => ['data' => ['config' => ['componentType' => Container::NAME, 'component' => 'Magento_Ui/js/form/components/group', 'visible' => true, 'label' => __('Country/State')]]], 'children' => ['country' => ['arguments' => ['data' => ['config' => ['dataType' => Text::NAME, 'formElement' => Select::NAME, 'componentType' => Field::NAME, 'dataScope' => 'country', 'visible' => true, 'options' => $this->getCountries(), 'validation' => ['required-entry' => true]]]]], 'state' => ['arguments' => ['data' => ['config' => ['componentType' => Field::NAME, 'dataType' => Text::NAME, 'formElement' => Select::NAME, 'component' => 'Magento_Weee/js/regions-tax-select', 'dataScope' => 'state', 'options' => $this->getRegions(), 'filterBy' => ['field' => 'country'], 'caption' => '*', 'visible' => true]]]]]], 'value' => ['arguments' => ['data' => ['config' => ['componentType' => Field::NAME, 'formElement' => Input::NAME, 'dataType' => Price::NAME, 'label' => __('Tax'), 'enableLabel' => true, 'dataScope' => 'value', 'validation' => ['required-entry' => true]]]]], 'website_id' => ['arguments' => ['data' => ['config' => ['dataType' => Text::NAME, 'formElement' => Select::NAME, 'componentType' => Field::NAME, 'dataScope' => 'website_id', 'label' => __('Website'), 'visible' => $this->websiteManager->isMultiWebsites(), 'options' => $this->websiteManager->getWebsites($product, $eavAttribute)]]]], 'actionDelete' => ['arguments' => ['data' => ['config' => ['componentType' => 'actionDelete', 'dataType' => Text::NAME, 'label' => __('Action')]]]]]]]]);
 }
 /**
  * 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;
 }
Example #4
0
 protected function setUp()
 {
     parent::setUp();
     $this->sourceCountryMock = $this->getMockBuilder(SourceCountry::class)->disableOriginalConstructor()->getMock();
     $this->eavAttributeFactoryMock = $this->getMockBuilder(EavAttributeFactory::class)->setMethods(['create'])->disableOriginalConstructor()->getMock();
     $this->eavAttributeMock = $this->getMockBuilder(EavAttribute::class)->disableOriginalConstructor()->getMock();
     $this->websiteManagerMock = $this->getMockBuilder(WebsiteManager::class)->disableOriginalConstructor()->getMock();
     $this->eavAttributeFactoryMock->expects($this->any())->method('create')->willReturn($this->eavAttributeMock);
     $this->eavAttributeMock->expects($this->any())->method('loadByCode')->willReturn($this->eavAttributeMock);
 }
Example #5
0
 /**
  * Load the localized version of an attribute.
  * This code uses a local cache to ensure correct performance during indexing.
  *
  * @param AttributeInterface|int $attribute Product attribute.
  * @param integer                $storeId   Store id.
  *
  * @return \Magento\Catalog\Api\Data\EavAttributeInterface
  */
 private function getAttributeByStore($attribute, $storeId)
 {
     $attributeId = $this->getAttributeId($attribute);
     if (!isset($this->storeAttributes[$storeId]) || !isset($this->storeAttributes[$storeId][$attributeId])) {
         /**
          * @var EavAttributeInterface
          */
         $storeAttribute = $this->attributeFactory->create();
         $storeAttribute->setStoreId($storeId)->load($attributeId);
         $this->storeAttributes[$storeId][$attributeId] = $storeAttribute;
     }
     return $this->storeAttributes[$storeId][$attributeId];
 }
 /**
  * @param array $fixtures
  * @throws \Exception
  */
 public function install(array $fixtures)
 {
     $attributeCount = 0;
     foreach ($fixtures as $fileName) {
         $fileName = $this->fixtureManager->getFixture($fileName);
         if (!file_exists($fileName)) {
             continue;
         }
         $rows = $this->csvReader->getData($fileName);
         $header = array_shift($rows);
         foreach ($rows as $row) {
             $data = [];
             foreach ($row as $key => $value) {
                 $data[$header[$key]] = $value;
             }
             $data['attribute_set'] = explode("\n", $data['attribute_set']);
             /** @var \Magento\Catalog\Model\ResourceModel\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->getDefaultStoreView()->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->eavConfig->clear();
 }
Example #7
0
 public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
 {
     $installer = $setup;
     $installer->startSetup();
     $attributeSetCollection = $this->eavEntitiyType->loadByCode('catalog_product')->getAttributeSetCollection();
     $entityTypeId = $this->eavEntitiyType->loadByCode('catalog_product')->getId();
     $model = $this->attributeFactory->create();
     $data['attribute_code'] = 'is_featured';
     $data['is_user_defined'] = 1;
     $data['frontend_input'] = 'boolean';
     $data += ['is_filterable' => 0, 'is_filterable_in_search' => 0, 'apply_to' => []];
     $data['backend_type'] = $model->getBackendTypeByInput($data['frontend_input']);
     $data['default_value'] = 0;
     $data['frontend_label'] = 'Is Featured';
     $model->addData($data);
     $model->setEntityTypeId($entityTypeId);
     $model->setIsUserDefined(1);
     try {
         foreach ($attributeSetCollection as $attributeSet) {
             $attributeSetId = $attributeSet->getId();
             $groupCollection = $this->groupCollectionFactory->create()->setAttributeSetFilter($attributeSetId)->load();
             $groupCode = 'product-details';
             $attributeGroupId = null;
             foreach ($groupCollection as $group) {
                 if ($group->getAttributeGroupCode() == $groupCode) {
                     $attributeGroupId = $group->getAttributeGroupId();
                     break;
                 }
             }
             $model->setAttributeSetId($attributeSetId);
             $model->setAttributeGroupId($attributeGroupId);
             $model->save();
         }
     } catch (\Exception $e) {
         echo $this->messageManager->addError($e->getMessage());
     }
     $installer->endSetup();
 }
 /**
  * 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();
     $groups = $set->getGroups();
     if (is_array($groups)) {
         foreach ($groups 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;
 }
Example #9
0
 /**
  * Add new product attrubute into all attribute sets.
  * If attribute is already exists - skip.
  *
  * @param  array $data Array of slider data arrays
  * <pre>
  * [
  *     attribute_code
  *     is_global
  *     frontend_input [text|boolean|textarea|select|price|media_image|etc]
  *     default_value_text
  *     is_searchable
  *     is_visible_in_advanced_search
  *     is_comparable
  *     frontend_label array
  *     sort_order Set 0 to use MaxSortOrder
  * ]
  * </pre>
  * @return void
  */
 public function execute($data)
 {
     $defaults = array('is_global' => 0, 'frontend_input' => 'boolean', 'is_configurable' => 0, 'is_filterable' => 0, 'is_filterable_in_search' => 0, 'sort_order' => 1);
     $entityTypeId = $this->objectManager->create('Magento\\Eav\\Model\\Entity')->setType(\Magento\Catalog\Model\Product::ENTITY)->getTypeId();
     $attributeSets = $this->objectManager->create('Magento\\Eav\\Model\\ResourceModel\\Entity\\Attribute\\Set\\Collection')->setEntityTypeFilter($entityTypeId);
     foreach ($data as $itemData) {
         /* @var $model \Magento\Catalog\Model\ResourceModel\Eav\Attribute */
         $model = $this->attributeFactory->create()->load($itemData['attribute_code'], 'attribute_code');
         if ($model->getId()) {
             continue;
         }
         $itemData = array_merge($itemData, $defaults);
         $itemData['source_model'] = $this->productHelper->getAttributeSourceModelByInputType($itemData['frontend_input']);
         $itemData['backend_model'] = $this->productHelper->getAttributeBackendModelByInputType($itemData['frontend_input']);
         $itemData['backend_type'] = $model->getBackendTypeByInput($itemData['frontend_input']);
         $model->addData($itemData);
         $model->setEntityTypeId($entityTypeId);
         $model->setIsUserDefined(1);
         foreach ($attributeSets as $set) {
             $model->setAttributeSetId($set->getId());
             $model->setAttributeGroupId($set->getDefaultGroupId());
             try {
                 $model->save();
             } catch (\Exception $e) {
                 $this->fault('product_attribute_save', $e);
             }
         }
         if (!$attributeSets->count()) {
             try {
                 $model->save();
             } catch (\Exception $e) {
                 $this->fault('product_attribute_save', $e);
             }
         }
     }
 }
Example #10
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\ResourceModel\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/*/');
 }
 /**
  * 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\ResourceModel\Eav\Attribute
  */
 public function getAttributeById($attributeId, $product)
 {
     $attribute = parent::getAttributeById($attributeId, $product);
     return $attribute ?: $this->_eavAttributeFactory->create()->load($attributeId);
 }
Example #12
0
 /**
  * Load attribute model by attribute data object.
  *
  * TODO: This method should be eliminated when all missing service methods are implemented
  *
  * @param ProductAttributeInterface $attribute
  * @return EavAttribute
  */
 private function getAttributeModel($attribute)
 {
     return $this->eavAttributeFactory->create()->load($attribute->getAttributeId());
 }