[Yii2] How to translate data from db and display in a dropDownList?

Hi all, here is my code




    <?php

             

        $dataList= ArrayHelper::map(ProfileCat::find()->orderBy('order')->all(),'id','description');    

        echo $form->field($profile, 'cat')->dropDownList($dataList, 

         ['prompt'=>'-Choose a Category-']) ;

    ?>    

 



I want to translate using Yii:t() the data of the field ‘description’ in the current user language.

What is the best way?

Thank’s

For now i solve in this way:

  1. I create a new Component "Common.php" like this:



namespace app\components;


use Yii;

use yii\helpers\Html;




class Common 

{

        public static function transarray($array) {

         

            foreach ($array as $key => $value) {

                $array[$key] = Yii::t('stz', $value);

            }   

            

         return $array;   

        }


}



and then my new code become:




        $dataList= Common::transarray(ArrayHelper::map(ProfileCat::find()->orderBy('order')->all(),'id','description'));    

        echo $form->field($profile, 'cat')->dropDownList($dataList, 

         ['prompt'=>Yii::t('stz','-Choose a Category-')]) ;




I don’t know if there’s a better method but at the moment form me it works fine. ;)

You can also extend Class yii\helpers\ArrayHelper and re-implement map() method as follows:




    public static function map($array, $from, $to, $group = null)

    {

        $result = [];

        foreach ($array as $element) {

            $key = static::getValue($element, $from);

            $value = static::getValue($element, $to);

            if ($group !== null) {

                $result[static::getValue($element, $group)][$key] = $value;

            } else {

                $result[$key] = Yii::t('app',$value);

            }

        }


        return $result;

    }



Remember the


use Yii

line after namspace declaration.

1 Like

Hello Frederico,

I use your solution.

Thank you!




<?= $form->field($model, 'gender_id')->

dropDownList(Common::transArray($model->genderList), 

['prompt' => Yii::t('app', 'Please Choose One')]); ?>



Incredible! :D

Glad to help someone.