Skip to content

Instantly share code, notes, and snippets.

@0-Sony
Created August 24, 2023 10:15
Show Gist options
  • Save 0-Sony/af7474ac1fc97eabb2c79cb3ac62b5a5 to your computer and use it in GitHub Desktop.
Save 0-Sony/af7474ac1fc97eabb2c79cb3ac62b5a5 to your computer and use it in GitHub Desktop.
Magento2 : Update Customer Attribute for specific Website with DataPatch
<?php
declare(strict_types=1);
namespace MyNamespace\MyModule\Setup\Patch\Data;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Model\Customer;
use Magento\Eav\Api\AttributeRepositoryInterface;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Store\Model\StoreManagerInterface;
class UpdateCustomerAttribute implements DataPatchInterface
{
public function __construct(
private readonly ModuleDataSetupInterface $moduleDataSetup,
private readonly StoreManagerInterface $storeManager,
private readonly AttributeRepositoryInterface $attributeRepository
) {
}
/**
* @inheritDoc
*/
public function getAliases(): array
{
return [];
}
/**
* @inheritDoc
*/
public static function getDependencies(): array
{
return [];
}
/**
* @inheritDoc
*/
public function apply(): self
{
$websitesByCode = $this->storeManager->getWebsites(false, true);
$attribute = $this->attributeRepository->get(Customer::ENTITY, CustomerInterface::DOB);
$fields = [
'attribute_id' => $attribute->getId(),
'website_id' => $websitesByCode['my_website_code']->getId(),
'is_visible' => true,
];
$this->moduleDataSetup->getConnection()->insertOnDuplicate(
$this->moduleDataSetup->getTable('customer_eav_attribute_website'),
$fields
);
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment