i'm working on a 2.1.9 magento2 CE installation,

i've added a custom attribute to the customer, everything it's working OK, but when the attribute is not set and I try to retrieve it with the code

$customer->getCustomAttributes()["custom_field"]->getValue() I get an exception, instead a null value.

if the attribute is set on the customer this method will retur the correct data.

the exception is this one:

Exception #0 (Exception): Notice: Undefined index: custom_field in /var/www/magento/[INSTALLATION_DIR]/app/design/frontend/[TEMPLATE_DIR]/Magento_Customer/templates/form/edit.phtml on line 33

Exception #0 (Exception): Notice: Undefined index: custom_field in /var/www/magento/[INSTALLATION_DIR]/app/design/frontend/[TEMPLATE_DIR]/Magento_Customer/templates/form/edit.phtml on line 33

in phtml files right now i'm working with a try catch block to avoid the exception, but when I'm working on a plugin the exception will stop the execution even in a try catch block.

any suggestion to check if custom attribute exist?



Templates are not responsible for handle any logic, so any try catch block inside of template is a blasphemy.

Put your logic in block. I imagine you can do something like:

public function getCustomfield()
    return !empty($customer->getCustomAttributes()["custom_field"]) ? $customer->getCustomAttributes()["custom_field"]->getValue() : '';

Then call it in your template.


Use below code in phtml:

<?php echo $block->escapeHtml($_helper->getCustomerAttributeValue($this->getCustomer()->getId(), 'custom_field')); ?>


 * {@inheritdoc}
public function getCustomerAttributeValue($customerId, $attributeCode)
    $customerObject = $this->_customerFactory->create()->load($customerId);
    return $customerObject->getData($attributeCode);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.