Set custom Customer attribute value programmatically Magento 2 - magento

I am importing some customers with :
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerFactory = $objectManager->create('\Magento\Customer\Model\CustomerFactory');
$customer = $objectManager->create('Magento\Customer\Model\Customer')->setWebsiteId(1)->loadByEmail('customrr#custom.com');
try {
if(!empty($customer->getData('email')))
{
$customer->setAttr1(1); // Attr1 = Name of the custom Attribute
$customer->setAttr2(2); // Attr2 = Name of the custom Attribute
}
else
{
$customer = $customerFactory->create()->setWebsiteId(1);
}
$customer->setLastname("Lastname");
$customer->setFirstname("Firsty");
.....
$customer->save();
The customer is saved with all his standard attributes correctly but my new attributes won't be saved anyway. I've also tried :
$customer->setCustomAttribute('Attr1','value');
but this didn't work too.
The custom Attribute are shown correclty in Magentos 2 backoffice and the values are saved correctly too if creating a customer manually.

Have you tried:
$customer-> setData('Attr1','value');
and don't forget to save and log the information:
try {
$customer->save();
} catch (\Exception $e) {
// log exception so you can debug the issue if there is one
}

<?php
namespace Custom\Module\Setup;
use Magento\Eav\Model\Config;
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;
class InstallData implements InstallDataInterface
{
private $eavSetupFactory;
public function __construct(
EavSetupFactory $eavSetupFactory,
Config $eavConfig
) {
$this->eavSetupFactory = $eavSetupFactory;
$this->eavConfig = $eavConfig;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'custom_attribute', [
'label' => 'Label',
'system' => 0,
'position' => 720,
'sort_order' => 720,
'visible' => true,
'note' => '',
'type' => 'int',
'input' => 'boolean',
'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
'backend' => \Custom\Module\Model\Customer\Attribute\Backend\DoWHatEver::class,
]
);
$attribute = $this->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'custom_attribute');
$attribute->addData([
'is_user_defined' => 1,
'is_required' => 0,
'default_value' => 0,
'used_in_forms', ['adminhtml_customer']
])->save();
}
public function getEavConfig()
{
return $this->eavConfig;
}
}

Related

The "componentType" configuration parameter is required for the "" component

I created a custom module. My module adds the custom attribute to product. Now when I try to add New Product in Magento 2.4.4 , I am getting The "componentType" configuration parameter is required for the "" component. error
Here is My code for InstallData.php
<?php
namespace Vendor\Module\Setup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
private $eavSetupFactory;
public function __construct(EavSetupFactory $eavSetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
}
/**
* {#inheritdoc}
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
) {
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'mcwarehouse',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'label' => 'Warehouse',
'input' => 'select',
'source' => \Vendor\Module\Model\Product\Attribute\Source\Warehouse::class,
'backend_model' =>\Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend::class,
'required' => false,
'sort_order' => 50,
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
'group' => 'Product Details',
'is_used_in_grid' => true,
'is_visible_in_grid' => false,
'is_filterable_in_grid' => false
]
);
}
}
The error I got is
1 exception(s):
Exception #0 (Magento\Framework\Exception\LocalizedException): The "componentType" configuration parameter is required for the "" component.

How to get the users detail info in api call in cs-cart?

I am trying to retrieve user information through api in CS-cart. But it returns only limited information. How can we modify the code to get all the user info for ex- user profiles, address, gst and all.
you can create your own API.
/var/www/html/app/addons/addon_name/Tygh/Api/Entities/Egg.php
<?php
namespace Tygh\Api\Entities;
use Tygh\Api\AEntity;
use Tygh\Api\Response;
class Egg extends AEntity
{
public function index($id = '', $params = array())
{
if(empty($id))
{
$dd=db_get_array("SELECT * FROM ?:table_name");
//result all rows
}
else
{
// for filtering purpose
$where=array("id"=>$id);
$dd=db_get_array("SELECT * FROM ?:table_name where ?w",$where);
//result-> specific one row
}
return array(
'status' => Response::STATUS_OK,
'data' => $dd
);
}
public function create($params)
{
return array(
'status' => Response::STATUS_OK,
'data' => array()
);
}
public function update($id, $params)
{
return array(
'status' => Response::STATUS_OK,
'data' => array()
);
}
public function delete($id)
{
return array(
'status' => Response::STATUS_NO_CONTENT,
);
}
public function privileges()
{
return array(
'index' => true,
'create' => 'create_things',
'update' => 'edit_things',
'delete' => 'delete_things',
'index' => 'view_things'
);
}
public function privilegesCustomer()
{
return array(
'index' => true
);
}
}
?>
Remarks:
file name,
class name,
file path
Or you can edit the user API entity from this location.
app/Tygh/Api/Entities/Users.php
Any doubts , then kick me in...

Magetno 2 : Custom Attribute is not working

I have created custom attribute programmatically. it is not showing in product section in admin panel.I used following commands after create InstallData.php & Options.php files :
php bin/magento setup:upgrade
php bin/magento cache:clean
After it i am not able to find custom attribute on product section in admin.
Code is
1 Create InstallData.php
namespace Matrixsoftware\Matrix\Setup;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory /* For Attribute create */;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
private $eavSetupFactory;
public function __construct(EavSetupFactory $eavSetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
/** #var EavSetup $eavSetup */
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'thickness',/* Custom Attribute Code */
[
'group' => 'Product Details',/* Group name in which you want
to display your custom attribute */
'type' => 'int',/* Data type in which formate your value save in database*/
'backend' => '',
'frontend' => '',
'label' => 'Choose Thickness', /* lablel of your attribute*/
'input' => 'select',
'class' => '',
'source' => 'Matrixsoftware\Matrix\Model\Config\Source\Options',
/* Source of your select type custom attribute options*/
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
/*Scope of your attribute */
'visible' => true,
'required' => true,
'user_defined' => false,
'default' => '',
'searchable' => false,
'filterable' => true,
'comparable' => false,
'visible_on_front' => true,
'used_in_product_listing' => true,
'unique' => false
]
);
$setup->endSetup();
}
}
2.Create Options.php
namespace Matrixsoftware\Matrix\Model\Config\Source;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory;
use Magento\Framework\DB\Ddl\Table;
class Options extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
protected $optionFactory;
/*public function __construct(OptionFactory $optionFactory)
{
$this->optionFactory = $optionFactory;
//you can use this if you want to prepare options dynamically
}*/
public function getAllOptions()
{
/* your Attribute options list*/
$this->_options=[ ['label'=>'Select Options', 'value'=>''],
['label'=>'Option1', 'value'=>'1']
['label'=>'Option2', 'value'=>'2']
['label'=>'Option3', 'value'=>'3']
];
return $this->_options;
}
public function getOptionText($value)
{
foreach ($this->getAllOptions() as $option) {
if ($option['value'] == $value) {
return $option['label'];
}
}
return false;
}
public function getFlatColumns()
{
$attributeCode = $this->getAttribute()->getAttributeCode();
return [
$attributeCode => [
'unsigned' => false,
'default' => null,
'extra' => null,
'type' => Table::TYPE_INTEGER,
'nullable' => true,
'comment' => 'Custom Attribute Options ' . $attributeCode . ' column',
],
];
}
}
You use this as well, as I used to create custom product attributes programatically.
app/code/[Vendor]/[Module]/Setup/InstallData.php
namespace [Vendor]\[Module]\Setup;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Sales\Setup\SalesSetupFactory;
use Magento\Quote\Setup\QuoteSetupFactory;
class InstallData implements InstallDataInterface
{
private $eavSetupFactory;
private $quoteSetupFactory;
private $salesSetupFactory;
/**
* InstallData constructor.
* #param EavSetupFactory $eavSetupFactory
* #param QuoteSetupFactory $quoteSetupFactory
*/
public function __construct(
EavSetupFactory $eavSetupFactory,
QuoteSetupFactory $quoteSetupFactory,
SalesSetupFactory $salesSetupFactory
)
{
$this->eavSetupFactory = $eavSetupFactory;
$this->quoteSetupFactory = $quoteSetupFactory;
$this->salesSetupFactory = $salesSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$quoteSetup = $this->quoteSetupFactory->create(['setup' => $setup]);
$salesSetup = $this->salesSetupFactory->create(['setup' => $setup]);
/**
* Add attributes to the eav/attribute
*/
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'dropdown_attribute',
[
'type' => 'int',
'label' => 'Dropdown Attribute',
'input' => 'select',
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => '',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => false,
'unique' => false,
'option' => [
'values' => [
'Option 1',
'Option 2',
'Option 3'
],
]
]
);
$attributeSetId = $eavSetup->getDefaultAttributeSetId('catalog_product');
$eavSetup->addAttributeToSet(
'catalog_product',
$attributeSetId,
'General',
'dropdown_attribute'
);
$attributeOptions = [
'type' => Table::TYPE_TEXT,
'visible' => true,
'required' => false
];
}
}

Magento invoice grid filter_condition_callback not working

I added a custom column to invoice grid using an observer.
The problem is that I can't sort or filter by the new column.
I added a filter condition callback but the function is not called.
Here is my Observer.php
class DB_CustomGrid_Model_Adminhtml_Observer
{
public function onBlockHtmlBefore(Varien_Event_Observer $observer)
{
$block = $observer->getBlock();
$payment_methods = array();
$readConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
$query = 'SELECT method FROM '.Mage::getSingleton('core/resource')->getTableName('sales/order_payment').' GROUP BY method';
$methods = $readConnection->fetchAll($query);
foreach($methods as $payment) {
if($payment["method"] !== 'free') {
$payment_methods[$payment["method"]] = Mage::getStoreConfig('payment/'.$payment["method"].'/title');
}
}
switch ($block->getType()) {
case 'adminhtml/sales_invoice_grid':
$block->addColumnAfter('state', array(
'header' => Mage::helper('sales')->__('Payment Method'),
'index' => 'method',
'type' => 'options',
'width' => '70px',
'options' => $payment_methods,
'filter' => false,
'filter_condition_callback' => array($this, '_myCustomFilter'),
), 'method');
break;
}
}
public function beforeCollectionLoad(Varien_Event_Observer $observer)
{
$collection = $observer->getOrderInvoiceGridCollection();
$collection->join(array('payment'=>'sales/order_payment'),'main_table.order_id=parent_id',array('method'));
}
protected function _myCustomFilter($collection, $column)
{
exit;
if (!$value = $column->getFilter()->getValue()) {
return $collection;
}
$collection->getCollection()->getSelect()->where("sales_order_payment.method like ?", "%$value%");
return $collection;
}
}
I added an exit; to check if the function is called or not.
Try this:
Add a new protected function to your observer class:
protected function _callProtectedMethod($object, $methodName) {
$reflection = new ReflectionClass($object);
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invoke($object);
}
Then call $block->sortColumnsByOrder() and the new function $this->_callProtectedMethod($block, '_prepareCollection') directly after $block->addColumnAfter();

can't Filter or search product in grid with custom renderer

I have a problem with filter in my module in admin grid.
I also used 'order_item_id' field in my custom table and fetching product name based on '(sales/order_item)' using renderer.
I also using " 'filter_condition_callback' => array($this, '_productFilter') " but it cant' work
My problem is: can't Filter for columns with custom renderer not working.
When i search product name in column,it returns zero records.
What i wrong in My Code ?
public function _prepareColumns()
{
$this->addColumn('entity_id', array(
'header' => Mage::helper('adminhtml')->__('ID'),
'align' =>'right',
'width' => '50px',
'index' => 'entity_id',
));
$this->addColumn('order_item_id', array(
'header' => Mage::helper('adminhtml')->__('Product Name'),
'align' =>'right',
'index' => 'order_item_id',
'renderer' => 'Test_Module1_Block_Adminhtml_Renderer_Product',
'filter_condition_callback' => array($this, '_productFilter'),
));
return parent::_prepareColumns();
}
protected function _productFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$this->getCollection()->getSelect()->where(
"order_item_id like ?
"
, "%$value%");
return $this;
}
my renderer is
class Test_Module1_Block_Adminhtml_Renderer_Product extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
public function render(Varien_Object $row)
{
$order = Mage::getModel('sales/order_item')->load($row->getData('order_item_id'));
return $order->getName();
}
}
It is because of you have rendered id and you are searching with product name. So you need to change your productfilter function and put code for search the id in table according to product name.
You need to change your function :
protected function _productFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$orderitem = Mage::getModel('sales/order_item')->getCollection();
$orderitem->addFieldToFilter('name',array('like'=>'%'.$value.'%'));
$ids =array();
foreach($orderitem as $item){
$ids[] = $item->getId();
}
$this->getCollection()->addFieldToFilter("id",array("in",$ids));
return $this;
}
I have done some changes on saumik code and its work for me.
protected function _productFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$orderitem = Mage::getModel('sales/order_item')->getCollection();
$orderitem->addFieldToFilter('name',array('like'=>'%'.$value.'%'));
$ids =array();
foreach($orderitem as $item){
$ids[] = $item->getOrderId(); // sales_flat_order_item.order_id = sales_flat_order.entity_id
}
$this->getCollection()->addFieldToFilter("entity_id",array("in",$ids));
return $this;
}

Resources