Book Image

Magento 2 Development Cookbook

Book Image

Magento 2 Development Cookbook

Overview of this book

With the challenges of growing an online business, Magento 2 is an open source e-commerce platform with innumerable functionalities that gives you the freedom to make on-the-fly decisions. It allows you to customize multiple levels of security permissions and enhance the look and feel of your website, and thus gives you a personalized experience in promoting your business.
Table of Contents (18 chapters)
Magento 2 Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Programmatically adding product attributes


In the recipe Creating an install and upgrade script, we learned how we can automate the execution of database changes.

In these install scripts, we can also add attributes to products, as we will learn in this recipe.

Getting ready

We will work further on the Packt_HelloWorld module that we have created in the previous recipes. Make sure you have the module installed.

How to do it...

The following steps describe the procedure to create an upgrade script that adds a product attribute to all products:

  1. The module Packt_HelloWorld is already installed in our system so we have to create an upgrade script. Create the file UpgradeData.php in the folder app/code/Packt/HelloWorld/Setup. Add the following content in that file:

    <?php
    namespace Packt\HelloWorld\Setup;
    
    use Magento\Framework\Setup\UpgradeDataInterface;
    use Magento\Framework\Setup\ModuleContextInterface;
    use Magento\Framework\Setup\ModuleDataSetupInterface;
    
    class UpgradeData implements UpgradeDataInterface...