Magento 2 Create Yes No Attribute Programmatically

This tutorial is about Create Yes No Attribute Programmatically in Magento 2. Obviously, there are many ways and techniques of doing a task but if you are looking for a better and dynamic way then this tutorial may satisfy your needs. Creating Yes No attributes programmatically in Magento 2 is explained below. Let’s have a look at how we can do this.

Here I am creating the upgradeData script that will add custom product attribute with yes and no options.

<?php
 namespace QaisarSatti\HelloWorld\Setup;

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

class upgradeData implements UpgradeDataInterface {
 private $eavSetupFactory;
 protected $logger;

public function __construct(EavSetupFactory $eavSetupFactory,\Psr\Log\LoggerInterface $logger) {
 $this->eavSetupFactory = $eavSetupFactory;
 $this->logger = $logger;
 }

public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
 
 
 $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
 $eavSetup->addAttribute(
 \Magento\Catalog\Model\Product::ENTITY,
 'subscripion_product',[
 'type' => 'text',
 'backend' => '',
 'frontend' => '',
 'label' => 'Enable Subscription',
 'input' => 'select',
 'class' => '',
 'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
 'visible' => true,
 'required' => true,
 'user_defined' => false,
 'default' => '',
 'searchable' => false,
 'filterable' => false,
 'comparable' => false,
 'visible_on_front' => false,
 'used_in_product_listing' => true,
 'unique' => false,
 'apply_to' => ''
 ]
 );
 
 
 }
 
 }

That’s it from this tutorial. I strongly believe there is always room for improvement. So I am open to any suggestion and feedback. Please feel free to leave hat you are thinking in the comments section below. Cheers.

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply