Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
product_simple_with_custom_attribute.php
Go to the documentation of this file.
1 <?php
7 include __DIR__ . '/product_simple_with_full_option_set.php';
8 
11 
13 $productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
14 
16 $installer = $objectManager->create(\Magento\Catalog\Setup\CategorySetup::class);
17 $entityModel = $objectManager->create(\Magento\Eav\Model\Entity::class);
18 $attributeSetId = $installer->getAttributeSetId('catalog_product', 'Default');
19 $entityTypeId = $entityModel->setType(\Magento\Catalog\Model\Product::ENTITY)->getTypeId();
20 $groupId = $installer->getDefaultAttributeGroupId($entityTypeId, $attributeSetId);
21 
23 $attribute = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class);
24 $attribute->setAttributeCode(
25  'attribute_code_custom'
26 )->setEntityTypeId(
28 )->setIsVisible(true)->setFrontendInput(
29  'text'
30 )->setFrontendLabel(
31  'custom_attributes_frontend_label'
32 )->setAttributeGroupId(
33  $groupId
34 )->setIsFilterable(
35  1
36 )->setIsUserDefined(
37  1
38 )->setBackendType(
39  $attribute->getBackendTypeByInput($attribute->getFrontendInput())
40 )->save();
41 
42 $product = $productRepository->get('simple', true);
43 
44 $product->setCustomAttribute($attribute->getAttributeCode(), 'customAttributeValue');
45 
defined('TESTS_BP')||define('TESTS_BP' __DIR__
Definition: _bootstrap.php:60