Создайте простой продукт программно в magento2

Мадженто-2:

как программно создать простой продукт извне magento-2


person Vinoth kumar    schedule 01.12.2015    source источник


Ответы (2)


Я не знаю, что вы имеете в виду под внешним, но мне удалось создать продукт с помощью magerun2. . Вот как далеко я продвинулся:

# bin/n98-magerun2.phar dev:console

$productFactory = $objectManager->create("\Magento\Catalog\Model\ProductFactory");

// this needs to be set to avoid exception:
// Magento\Framework\Exception\SessionException with message 'Area code not set: Area code must be set before starting a session.'
// I don't know why ...
$appState = $objectManager->get("Magento\Framework\App\State")
$appState->setAreaCode("de")

$product = $productFactory->create()

$product->setName("FooBar")
$product->setName("123")
$product->setAttributeSetId(15)

$product->save()
person bka    schedule 23.12.2015
comment
Спасибо, я тоже нашел решение - person Vinoth kumar; 21.04.2016
comment
de не является кодом города, вот список областей, которые вы можете использовать, в зависимости от ваших потребностей: devdocs.magento.com/guides/v2.2/architecture/archi_perspectives/ - person tawfekov; 23.08.2018

Используйте REST API вашего экземпляра Magneto 2: http://mage.host.com/index.php/rest/...

Вы можете получить определение OpenAPI (аналог WSDL для REST) ​​на http://mage.host.com/index.php/rest/default/schema/

Получите токен авторизации на первый шаг:

$ curl -X POST "http://mage.host.com/index.php/rest/V1/integration/admin/token" -H "Content-Type:application/json" -d '{"username":"admin", "password":"..."}'
"uhb..."

Затем опубликуйте новые данные о продукте, используя токен авторизации и минимальные атрибуты для нового продукта (4 — это идентификатор по умолчанию для атрибута продукта, установленного в пустом экземпляре Magento) и получите в ответ данные о новых продуктах:

$ curl -X POST "http://mage.host.com/index.php/rest/V1/products" -H "Content-Type:application/json" -H "Authorization:Bearer uhb..." -d '{"product": {"sku": "sku01","name": "product 001","attribute_set_id": 4}}'
{"id":...,"sku":"sku01","name":"product 001","attribute_set_id":4,"status":..., ...

Это определение объекта продукта из OpenAPI (доступные атрибуты продукта для публикации):

{
  "catalog-data-product-interface": {
    "type": "object",
    "description": "",
    "properties": {
      "id": {"type": "integer", "description": "Id"},
      "sku": {"type": "string", "description": "Sku"},
      "name": {"type": "string", "description": "Name"},
      "attributeSetId": {"type": "integer", "description": "Attribute set id"},
      "price": {"type": "number", "description": "Price"},
      "status": {"type": "integer", "description": "Status"},
      "visibility": {"type": "integer", "description": "Visibility"},
      "typeId": {"type": "string", "description": "Type id"},
      "createdAt": {"type": "string", "description": "Created date"},
      "updatedAt": {"type": "string", "description": "Updated date"},
      "weight": {"type": "number", "description": "Weight"},
      "extensionAttributes": {"$ref": "#/definitions/catalog-data-product-extension-interface"},
      "productLinks": {
        "type": "array",
        "description": "Product links info",
        "items": {"$ref": "#/definitions/catalog-data-product-link-interface"}
      },
      "options": {
        "type": "array",
        "description": "List of product options",
        "items": {"$ref": "#/definitions/catalog-data-product-custom-option-interface"}
      },
      "mediaGalleryEntries": {
        "type": "array",
        "description": "Media gallery entries",
        "items": {"$ref": "#/definitions/catalog-data-product-attribute-media-gallery-entry-interface"}
      },
      "tierPrices": {
        "type": "array",
        "description": "List of product tier prices",
        "items": {"$ref": "#/definitions/catalog-data-product-tier-price-interface"}
      },
      "customAttributes": {
        "type": "array",
        "description": "Custom attributes values.",
        "items": {"$ref": "#/definitions/framework-attribute-interface"}
      }
    },
    "required": ["sku"]
  }
}

Переключите экземпляр Magento 2 в режим "разработчика" для получения сообщений об ошибках в ответах REST:

$ ./bin/magento deploy:mode:set developer
person Alex Gusev    schedule 18.03.2016