Skip to content

Magento 2: “Array to string conversion” error when adding customer attribute via Data Patch

I’m new to Magento 2 and trying to add a customer attribute using a Data Patch.

I created the following patch class:

<?php
namespace VendorModuleSetupPatchData;

use MagentoFrameworkSetupPatchDataPatchInterface;
use MagentoCustomerSetupCustomerSetupFactory;
use MagentoCustomerModelCustomer;
use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
use MagentoFrameworkSetupModuleDataSetupInterface;

class CreateQuickbooksInvoiceAttribute implements DataPatchInterface
{
    private $moduleDataSetup;
    private $customerSetupFactory;
    private $attributeSetFactory;

    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        CustomerSetupFactory $customerSetupFactory,
        AttributeSetFactory $attributeSetFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->customerSetupFactory = $customerSetupFactory;
        $this->attributeSetFactory = $attributeSetFactory;
    }

    public function apply()
    {
        $customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]);

        $customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();
        $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

        // Add attribute
        $customerSetup->addAttribute(Customer::ENTITY, 'quickbooks_invoice', [
            'type' => 'int',
            'label' => 'QuickBooks Invoice',
            'input' => 'select',
            'source' => MagentoEavModelEntityAttributeSourceBoolean::class,
            'required' => false,
            'visible' => true,
            'user_defined' => true,
            'system' => 0,
            'position' => 100,
            'sort_order' => 100,
            'default' => 0,
        ]);

        // Attach to forms
        $attribute = $customerSetup->getEavConfig()
            ->getAttribute(Customer::ENTITY, 'quickbooks_invoice')
            ->addData([
                'attribute_set_id' => $attributeSetId,
                'attribute_group_id' => $attributeGroupId,
                'used_in_forms' => ['adminhtml_customer'],
            ]);

        $attribute->save();
    }

    public static function getDependencies() { return []; }
    public function getAliases() { return []; }
}

Problem:

When I run:

php bin/magento setup:upgrade

I get the following error:

PHP Notice: Array to string conversion in /vendor/magento/framework/DB/Adapter/Pdo/Mysql.php on line 3170

It seems related to the used_in_forms array.

What I Tried:

Using addData([‘used_in_forms’ => [‘adminhtml_customer’]]).

Clearing cache and generated code.

Ensuring the attribute is not already in the database.

Converting the attribute to a CustomerModelAttribute object.