2012-10-10 17 views
9

Tengo un dropDownList en mi opinión, está poblando de clients tabla, la tabla contiene columnas como first_name, last_name, id etc., Ahora quiero muestran la first_name y last_name como texto de la pantalla y id como valor en la lista desplegable, he terminado con id como valor y como first_name texto de la pantalla, pero aquí quiero combinar esas columnas (first_name y last_name) y utilizar como texto de la pantalla.marco Yii cómo puedo combinar columnas y espectáculo como cadena de presentación de lista desplegable

en el modelo

function getClients() 
{ 
    $Clients = Client::model()->findAll(); 
    $list = CHtml::listData($Clients , 'client_id', 'first_name'); 
    return $list; 
} 

en vista

echo $form->dropDownList($model,'client_id',$model->getClients()); 

Respuesta

20

Heres otro método En el modelo

function getFullName() 
{ 
    return $this->first_name.' '.$this->last_name; 
} 

y

function getClients() 
{ 
    $Clients = Client::model()->findAll(); 
    $list = CHtml::listData($Clients , 'client_id', 'fullName'); 
    return $list; 
} 

Creo que este es un método poco reutilizable ya que se puede utilizar el attrib virtual fullName no solo en la lista desplegable sino en todas partes donde se necesita un nombre completo.

+1

@Kannan, es genial también :) más eficazmente, creo. Escribí mi ExtHtml hace 2 años. – Sergey

+0

Sí, esto es tan rápido y simple, y ahora estoy confundido para seleccionar la mejor respuesta ... :) de todos modos gracias @ dInGd0nG – nu6A

+0

después de algún experimento me di cuenta de que este método es adecuado para mi escenario cambiado. Y, en general, esto es apto ... así que estoy aceptando esto. – nu6A

7

primera variante (Fácil):

$list = array(); 
foreach ($Clients as $c) { 
    $list[$c->id] = $c->first_name . ' ' . $c->last_name; 
} 

segunda variante (Universal):

class ExtHtml extends CHtml { 
    public static function listData($models,$valueField,$textField,$groupField='') 
    { 
     $listData=array(); 
     if($groupField==='') 
     { 
      foreach($models as $model) 
      { 
       $value=self::value($model,$valueField); 
       if (is_array($textField)) { 
        $t = array(); 
        foreach ($textField as $field) { 
         $t[]=self::value($model,$field,$field); 
        } 
        $text=implode(' ', $t); 
       } else { 
        $text=self::value($model,$textField, null); 
        if ($text == null) { 
         if (is_callable($textField)) $text=call_user_func($textField, $model); 
         else $text = $textField; 
        } 
       } 
       $listData[$value]=$text; 
      } 
     } 
     else 
     { 
      foreach($models as $model) 
      { 
       $group=self::value($model,$groupField); 
       $value=self::value($model,$valueField); 
       if (is_array($textField)) { 
        $t = array(); 
        foreach ($textField as $field) { 
         $t[]=self::value($model,$field,$field); 
        } 
        $text=implode(' ', $t); 
       } else { 
        $text=self::value($model,$textField, null); 
        if ($text == null) { 
         if (is_callable($textField)) $text=call_user_func($textField, $model); 
         else $text = $textField; 
        } 
       } 
       $listData[$group][$value]=$text; 
      } 
     } 
     return $listData; 
    } 
    public static function value($model,$attribute,$defaultValue=null) 
    { 
     foreach(explode('.',$attribute) as $name) 
     { 
      if(is_object($model) && ($model->hasAttribute($name) || isset($model->{$name}))) 
       $model=$model->$name; 
      else if(is_array($model) && isset($model[$name])) 
       $model=$model[$name]; 
      else 
       return $defaultValue; 
     } 
     return $model; 
    } 
} 

// in model 

function getClients() 
{ 
    $Clients = Client::model()->findAll(); 
    $list = ExtHtml::listData($Clients , 'client_id', array('first_name', 'last_name')); 
    return $list; 
} 

tercera variante (MySQL)

function getClients() 
{ 
    $Clients = Client::model()->findAll(array('select' => 'concat(first_name, " ", last_name) as first_name')); 
    $list = CHtml::listData($Clients , 'client_id', 'first_name'); 
    return $list; 
} 
+0

wow !! .. u gracias @Sergey, yo después de la segunda manera, .. muchas gracias – nu6A

+1

@Kannan, en la segunda forma: si (is_callable ($ textField)) $ text = call_user_func ($ textField, $ model); - Puedes usarlo para obtener muchas variantes con la función de devolución de llamada – Sergey

+0

Sí, lo vi, eso es realmente genial. – nu6A

0

probar este modo compacto utilizando la función "función anónima" de PHP:

function getClients() 
    { 
     return CHtml::listData(Client::model()->findAll(), 'id', function($client) { return $client->first_name . ' ' . $client->last_name; }); 
    } 
0

comentario anterior con el "modo compacto" con función anónima tiene un error! código correcto es:

function getClients() 
{ 
    $clients = Client::model()->findAll(); 
    return CHtml::listData($clients, 'id', function($clients) { return $client->first_name . ' ' . $client->last_name; }); 
} 
Cuestiones relacionadas