Magento 2 – Different Ways to Get Field of a Collection

collection;magento2magic-getter

I have this helper class in Magento 2:

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $_countryFactory;

    public function __construct(
         \Magento\Directory\Model\CountryFactory $countryFactory
    )
    {
         $this->_countryFactory = $countryFactory;
    }

    public function getCountryIsoCode($country = 'US')
    {
          $country = $this->_countryFactory->create()->getCollection();
          $country->addFieldToFilter('country_id', array('eq' => country));

          $countryCode = $country->getFirstItem()->getIso3Code());
          $countryCode2 = $country->getFirstItem()->getData('iso3_code'));

          // $countryCode => null
          // $countryCode2 => 'USA'

          return $countryCode;
     }
}

The function getCountryIsoCode() has an example as parameter ('US').
I don't why the getIso3Code() doesn't work.
Instead the getData() works perfectly.

In Magento2 there aren't "php magic function to get database table field" anymore?
Is there something wrong in my code?

Best Answer

The problem is the 3 in the name.
I just tested and the magic getter does not play well with digits in the name.
The method getIso3Code does not exist, so, instead the method __call is called that is defined in Magento\Framework\DataObject.
The get part looks like this.

$key = $this->_underscore(substr($method, 3));
$index = isset($args[0]) ? $args[0] : null;
return $this->getData($key, $index);

the _underscore transforms the method name into the data key needed.
Here is the line that matters.

$result = strtolower(trim(preg_replace('/([A-Z]|[0-9]+)/', "_$1", $name), '_'));

I just ran this code on http://phpfiddle.org/ :

$name = 'iso3_code';
echo strtolower(trim(preg_replace('/([A-Z]|[0-9]+)/', "_$1", $name), '_'));

and to my surprise it showed iso_3_code but you expected iso3_code.

Related Topic