Hello Magento Lovers,

I have described how to add toggle (yes/no) attribute to the product using the setup install script.

We always need some features based on enable/disable or yes/no. Magento 2 has introduced a very attractive toggle button.

It's very simple to add using a Script. We can use either Install Data / Upgrade Data file in the setup directory based on our requirement, whether we are creating a module from scratch or we are modifying the existing module.

I have used InstallData.php in this post. 

 app/code/Vendor/Modulename/Setup/InstallData.php

    <?php

namespace Vendor\Module\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * Install Data Class (calls on  module installation)
 */
class InstallData implements InstallDataInterface
{
    /**
     * eav setup factory
     * @var object
     */
    private $eavSetupFactory;

    /**
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(
        EavSetupFactory $eavSetupFactory
    ) {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * install functionto add attributes
     *
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /**
         * eav setup object
         */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        /**
         * adding product attribute attribute_name 
         */
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'attribute_name',
            [
                'group' => 'General',
                'type' => 'int',
                'backend' => '',
                'frontend' => '',
                'label' => 'Enable Attribute',
                'input' => 'boolean',
                'class' => '',
                'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
                'visible' => true,
                'required' => false,
                'user_defined' => false,
                'default' => '1',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => false,
                'used_in_product_listing' => false,
                'unique' => false,
                'apply_to' => 'simple,configurable,virtual,bundle,downloadable'
            ]
        );

    }
}