Engine23
blogBannerImage
By Engine23

Magento - Concat part of a magento collection

When building admin area modules, you need to sometimes use the admin users. When doing so, you may want to combine the firstname and lastname into one. This is where concat comes in handy. It will combine them, into one string to be used as the visual for the dropdown. The following function will also show you how to get all the admin users using a collection.

    /*
    *  
    */
    public function getAdminUsersAsOptions()
    {

        $collection = Mage::getModel('admin/user')->getCollection()
                            ->addFieldToSelect('firstname')
                            ->addFieldToSelect('lastname')
                            ->addFieldToSelect('user_id');
        $collection->setOrder('lastname', 'ASC');
        $fields      = array('lastname', 'firstname');
        $fieldConcat = $collection->getConnection()->getConcatSql($fields, ', ');

        $collection->getSelect()->columns(array('value'=> 'user_id', 'name' => $fieldConcat));
        $items = $collection->getItems();
        $user_array = array();
        foreach($items as $_user)
        {
            $user_array[$_user->getData('user_id')] = $_user->getData('name');
        }
        return $user_array;
    }