Zend Framework: How to concatenate two columns and still use fetchPairs()?

10,200

Solution 1

protected function _getSelectOptions()
{
    $db     = Zend_Db_Table::getDefaultAdapter();
    $select = $db->select()->from('users', array(
        'id',
        'name' => new Zend_Db_Expr("CONCAT(first_name, ' ', lastname)"),
    ));

    return $db->fetchPairs($select);
}

Solution 2

This is only an idea, and fully untested, but you could try to use a Zend_Db_Expr:

$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select()->from(
   'users', 
    array('id', "CONCAT_WS(' ', first_name, last_name")
);
$roleOptions = $db->fetchPairs($select);
return $roleOptions;

From the Zend_Db documentation:

Example 15.55. Examples of specifying columns containing expressions

An expression with parentheses implicitly becomes a Zend_Db_Expr.

Share:
10,200
Mike
Author by

Mike

Updated on June 08, 2022

Comments

  • Mike
    Mike almost 2 years

    I have a form with a select element that I need to populate with values from a database. Specifically, the name and id of the current users. The fetchPairs() function works great for this! However, I need to concatenate the value from the first_name column and the last_name column and display this as the option label. Is there a way to do it and still use fetchPairs()? If not, how can I achieve the same result? Here's an excerpt of the code that is currently working:

    <?php // excerpt
    
    class Default_Form_AddUser extends Zend_Form
    {
        public function init()
        {
            $this->addElement('select', 'user', array(
                'label'      => 'Select user:',
                'required'   => true,
                'multiOptions' => $this->_getSelectOptions()
            ));
        }
    
        protected function _getSelectOptions()
        {
            $db = Zend_Db_Table::getDefaultAdapter();
            $select = $db->select()->from('users', array('id', 'first_name'));
            $roleOptions = $db->fetchPairs($select);
            return $roleOptions;
        }
    }