Radiolist shuffle methodology

Hello Experts,

I have a situation in a project, where four radiobutton appeared as a radiolist input. I want to shuffle the position of the correct value.

Can somebody help me how to do that??

Regards

Can you better explain what you want to do?

Hello Roberto,

Please see the below code, I have put in the view file.




<?= $form->field($model, 'user_selection')->radioList(['Option1'=>$opt1,'Option2'=>$opt2,'Option3'=>$opt3], ['onclick'=>'document.form-id.submit()'])->label(false); ?>



In this case page is get refreshed on submit. It is giving output as I wanted. Its working perfectly.

But every time the position of the options are fixed.

I want to shuffle the position of the options to be shuffled.

Like on first submit positions lets say "option1,option2,option3,option4. On next submit it will be like "option3,option2,option4, option1" etc.

Can you help me on this??

Regards

Sid

Something like this should help




<?php

function shuffle_arr($arr){

 $keys = array_keys($arr);

 shuffle($keys);

 foreach($keys as $key) {

  $shuffeled[$key] = $arr[$key];

 }

 return $shuffeled;

}


$form->field($model, 'user_selection')->radioList(shuffle_arr(['Option1'=>$opt1,'Option2'=>$opt2,'Option3'=>$opt3]), ['onclick'=>'document.form-id.submit()'])->label(false); ?>



no need to write shuffle function for array there is a native one in php

http://php.net/manual/en/function.shuffle.php

shuffle doesn’t keep the keys intact and you also can’t pass the vars to it like ‘opt’=>‘1’ (how yii needs it). I use shuffle in the function with array_keys to keep them intact. There could be a better way but that was just the first thing i thought to use. I’d put the function somewhere reusable so you don’t have it on the view page.