Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all articles
Browse latest Browse all 595

Magento 2 Basics Part 2

$
0
0

Read Magento 2 Basics Part 1

Get your Ecommerce flexibility using Magento 2

Magento 2 is the newest member of the Magento family, an open-source platform to accelerate your ecommerce goals. It has new and improved features that helps to increase user interaction and perform all business functions smoothly.

It basically integrates object-oriented programming with Relational DataBase Management System, while providing a Zend Framework in the background.

Just follow some simple steps described below to create category, products, and customers on your magento admin.

Programmatically Create Category, Products and Customer in Magento 2

With Magento 2 you can organise and administer your business data. Moreover its scalability feature allows you to make changes effortlessly.

Follow these simple steps given below to create category, products and customers.

Step 1: First Create the scripts/abstract.php file in magento root directory. Place the following code in the file.

<?php

use \Magento\Framework\AppInterface as AppInterface;
use \Magento\Framework\App\Http as Http;

use Magento\Framework\ObjectManager\ConfigLoaderInterface;
use Magento\Framework\App\Request\Http as RequestHttp;
use Magento\Framework\App\Response\Http as ResponseHttp;
use Magento\Framework\Event;
use Magento\Framework\Filesystem;
use Magento\Framework\App\AreaList as AreaList;
use Magento\Framework\App\State as State;

abstract class AbstractApp implements AppInterface
{
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager,
        Event\Manager $eventManager,
        AreaList $areaList,
        RequestHttp $request,
        ResponseHttp $response,
        ConfigLoaderInterface $configLoader,
        State $state,
        Filesystem $filesystem,
        \Magento\Framework\Registry $registry
    ) {
        $this->_objectManager = $objectManager;
        $this->_eventManager = $eventManager;
        $this->_areaList = $areaList;
        $this->_request = $request;
        $this->_response = $response;
        $this->_configLoader = $configLoader;
        $this->_state = $state;
        $this->_filesystem = $filesystem;
        $this->registry = $registry;
    }

    public function launch()
    {
        $this->run();
        return $this->_response;
    }

    abstract public function run();

    public function catchException(\Magento\Framework\App\Bootstrap $bootstrap, \Exception $exception)
    {
        return false;
    }
}
?>

Step 2: For Create category

Follow these subsequent steps

Step 2.1: Create scripts/createCategory.php file in magento root directory and place the code below to get category data.

<?php

require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class CreateProductApp extends AbstractApp
{

    public function run()
    {
        try{
            $this->_objectManager->get('Magento\Framework\Registry')
                ->register('isSecureArea', true);

            $category = $this->_objectManager->create('Magento\Catalog\Model\Category', 
                ['data' =>[
                    "parent_id" => 2, // Parent Category ID For Create As Subcategory for specific Parent Category
                    "name" => "Test Category", // Category Name
                    "is_active" => true, // True/False for active or deactive category
                    "position" => 2,
                    "include_in_menu" => true // For Hide/Show category in Main Menu
                ]
            ]);

            $category->setCustomAttributes([
                "display_mode"=> "PRODUCTS", // PRODUCTS => For show only Product / PAGE => For show only specific Static Page / PRODUCTS_AND_PAGE => For both Products and Static Page
                "is_anchor"=> "1", // 1 => set as anchor / 0 => set anchor No 
                "custom_use_parent_settings"=> "0",
                "custom_apply_to_products"=> "0",
                "url_key"=> "test-category", // for category url
                "url_path"=> "test-category",
                "automatic_sorting"=> "0"
                //'new_attribute' => 'value' // <-- your attribute
            ]);

            $repository = $this->_objectManager->get(\Magento\Catalog\Api\CategoryRepositoryInterface::class);
            $repository->save($category);

            if($repository)
            {
                echo "New Category Created.",'<br/>';
            }
        }
        catch(expetion $e)
        {
            echo $e;
        }
    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('CreateProductApp');
$bootstrap->run($app);
?>

Step 2.2: Run the command http://www.yourdomian.com/scripts/createCategory.php in your browser. This will create category.

Step 3: For Create Product (simple)

Follow these subsequent steps to create product (simple)

Step 3.1: Create scripts/createProduct.php file in magento root directory and place the code shown below in that file.

<?php

require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class CreateProductApp extends AbstractApp
{

    public function run()
    {
        $this->_objectManager->get('Magento\Framework\Registry')
            ->register('isSecureArea', false);

        $productFactory = $this->_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 = $this->_objectManager->get("Magento\Framework\App\State");
        $appState->setAreaCode("en");

        $baseUrl =  $this->_storeManager->getStore()->getBaseUrl(); // for base url

        try{

            $storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface'); 

            // Get Website ID
            $websiteId  = $storeManager->getWebsite()->getWebsiteId();

            $product = $productFactory->create();
            $product->setWebsiteIds(array($websiteId)); //website ID the product is assigned to, as an array
            $product->setSku('sku-test'); // Set your sku here
            $product->setName('Simple Test Product'); // Name of Product
            $product->setShortDescription("test short description"); //product short description
            $product->setDescription("test full description"); //product full description
            $product->setAttributeSetId(4); // Attribute set id, 4 => default Attribute set
            $product->setStatus(1); // Status on product enabled/ disabled 1/0
            $product->setWeight(10); // weight of product (if setProductHasWeight(1) than set wight value)
            $product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
            $product->setTaxClassId(0); // Tax class id
            $product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
            $product->setCategoryIds(array(3)); // set categories to product
            $product->setPrice(100); // price of product
            $product->setStockData(
                                    array(
                                        'use_config_manage_stock' => 0,
                                        'manage_stock' => 1,
                                        'is_in_stock' => 1,
                                        'qty' => 999 // product qty
                                    )
                                );
            $repository = $this->_objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
            $product = $repository->save($product);

            $productId = $product->getId();
            $product = $this->_objectManager->create('Magento\Catalog\Model\Product')->load($productId);

            // for add product image
            $fullImagePath = "/import/1.jpg"; // put product image in root-folder/pub/media/import folder
            if (file_exists("../pub/media".$fullImagePath)) {
                try {
                    $product->addImageToMediaGallery($fullImagePath, array('image', 'small_image', 'thumbnail'), true, false);;
                } catch (Exception $e) {
                    echo $e->getMessage();
                }
            } else {
                echo 'Can not find image<br/>';
            }

            /// Custome options ///
            $sku = $product->getSku();       
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); //instance of Object manager

            $values = array(
                                array(
                                    'title'=>'Red',
                                    'price'=>10,
                                    'price_type'=>"fixed",
                                    'sku'=>"Red1",
                                    'sort_order'=>1,
                                    'is_delete'=>0,
                                    'option_type_id'=>-1,
                                ),
                                array(
                                    'title'=>'White',
                                    'price'=>10,
                                    'price_type'=>"fixed",
                                    'sku'=>"White1",
                                    'sort_order'=>1,
                                    'is_delete'=>0,
                                    'option_type_id'=>-1,
                                ),
                                array(
                                    'title'=>'Black',
                                    'price'=>10,
                                    'price_type'=>"fixed",
                                    'sku'=>"black1",
                                    'sort_order'=>1,
                                    'is_delete'=>0,
                                    'option_type_id'=>-1,
                                )
                            );

            $options = array(
                                array(
                                    "sort_order"    => 1,
                                    "title"         => "Field Option",
                                    "price_type"    => "fixed",
                                    "price"         => "",
                                    "type"          => "field",
                                    "is_require"    => 0
                                ),
                                array(
                                    "sort_order"    => 2,
                                    "title"         => "Color",
                                    "price_type"    => "fixed",
                                    "price"         => "",
                                    "type"          => "drop_down",
                                    "is_require"    => 0,
                                    "values"        => $values
                                ),
                                array(
                                    "sort_order"    => 2,
                                    "title"         => "Multiple Option",
                                    "price_type"    => "fixed",
                                    "price"         => "",
                                    "type"          => "multiple",
                                    "values"        => $values,
                                    "is_require"    => 0
                                )
                            );

                    foreach ($options as $arrayOption) {
                        $product->setHasOptions(1);
                        $product->getResource()->save($product);
                        $option = $objectManager->create('\Magento\Catalog\Model\Product\Option')
                                ->setProductId($productId)
                                ->setStoreId($product->getStoreId())
                                ->addData($arrayOption);
                        $option->save();
                        $product->addOption($option);
                    }

            $product->save(); // save product

            echo "New Product created: ".$product->getName(); 
        }
        catch(expetion $e)
        {
            echo $e;
        }

    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('CreateProductApp');
$bootstrap->run($app);
?>

Step 3.2: Run command http://www.yourdomian.com/scripts/createProduct.php in your browser. This will create simple product with image and custom options.

Step 4: For Create Customer

Follow these subsequent steps to create customer

Step 4.1: Create scripts/createCustomer.php file in magento root directory and put below code to  get all the Customer data.

<?php

require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class CreateProductApp extends AbstractApp
{

    public function run()
    {
        $this->_objectManager->get('Magento\Framework\Registry')
            ->register('isSecureArea', false);

        try{

            $storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface'); 
            // Get Website ID
            $websiteId  = $storeManager->getWebsite()->getWebsiteId();

            // Instantiate object (this is the most important part)
            $customer   = $this->_objectManager->create('\Magento\Customer\Model\Customer');
            $customer->setWebsiteId($websiteId);

            // Preparing data for new customer
            $customer->setEmail("email@domain.com"); // Customer Email
            $customer->setFirstname("First Name"); // Customer First Name
            $customer->setLastname("Last name"); // Customer Last Name
            $customer->setPassword("password"); // Customer Password

            // Save data
            $customer->save();
            //$customer->sendNewAccountEmail(); // Send Email to Customer
            echo "Create New Customer: ".$customer->getFirstname()." ".$customer->getLastname();
        }
        catch(expetion $e)
        {
            echo $e;
        }

    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('CreateProductApp');
$bootstrap->run($app);
?>

Step 4.2: Run http://www.yourdomian.com/scripts/createCustomer.php  command in your browser. This will create customer in magento.

Hope this will help you!

Thank you.

Gordhan Chauhan

Gordhan Chauhan | Sr. Magento Developer

I work as Sr. Magento Developer in Yudiz Solutions Pvt. Ltd. -
a leading mobile apps, mobile games and web development company. I write blogs to share my knowledge and ideas to my audience. I am passionate about exploring and develop new stuff in magento and web development.

Viewing all articles
Browse latest Browse all 595

Trending Articles