Yii2: how to format a value in ActiveField? - php

On my form I have this:
echo $form->field($model, 'amount')->textInput();
If the value coming from the database is 42.5 I want to have it formatted with two decimals in the input field like this 42.50. How do I do that?
I don't find any info about formatting in ActiveField docs...

You could use formatter functionalities
$form->field($model, 'amount',
['inputOptions' => ['value' => Yii::$app->formatter->asDecimal($model->amount)]])
http://www.yiiframework.com/doc-2.0/yii-i18n-formatter.html
http://www.yiiframework.com/doc-2.0/guide-output-formatting.html

As an alternative to the #scaisEdge answer, you can also override/modify the value in the ActiveField renderer.
Here's an example for an ActiveField::textInput()
<?= $form->field($model, 'vat_rate')
->textInput([
'maxlength' => true,
'placeholder' => '0.00',
'value' => (float) $model->vat_rate * 100,
]) ?>

Related

jui/datepicker dateformat issue

I am using \yii\jui\DatePicker in my view.
when I provide input as 31/10/2017 it takes it as 31/Oct/2017.
However, when I provide input as 01/10/2017 it takes it as 10/Jan/2017 instead of 01/oct/2017 .
How can I specify input date format.
My code for it is:
echo $form->field($model, 'target_end_date')->widget(\yii\jui\DatePicker::classname(), [
'dateFormat' => 'php:d/M/Y',
'options'=>['style'=>'width:250px;', 'class'=>'form-control','readOnly'=>'readOnly', 'placeholder'=>'Select end date.']
]);
dateFormat is no longer the part of clientOptions and should be specified as follows:
<?= $form->field($model, 'target_end_date')->widget(\yii\jui\DatePicker::className(), [
'dateFormat' => 'php:d-m-Y',
]); ?>
Or, an alternative in ICU format:
'dateFormat' => 'dd/MM/yyyy',
See official docs for https://www.yiiframework.com/extension/yiisoft/yii2-jui/doc/api/2.0/yii-jui-datepicker#$dateFormat-detail property.
Simply Change your code
echo $form->field($model, 'target_end_date')->widget(\yii\jui\DatePicker::classname(), [
'dateFormat' => 'php:d/M/Y',
'options'=>['style'=>'width:250px;', 'class'=>'form-control','readOnly'=>'readOnly', 'placeholder'=>'Select end date.']
]);
To
echo $form->field($model, 'target_end_date')->widget(\yii\jui\DatePicker::classname(), [
'dateFormat' => 'php:d/m/Y',
'options'=>['style'=>'width:250px;', 'class'=>'form-control','readOnly'=>'readOnly', 'placeholder'=>'Select end date.']
]);
And for more date related formate refer below link.
http://php.net/manual/en/function.date.php

Yii2 - option default selection

i have the below form field of dropdown list.My problem is default option selected is not happening.The option value is coming as POST request.
$_REQUEST['id']=8;
<?= $form->field($model, 'id')->dropDownList(ArrayHelper::map($model,'id','name'),
[
isset($_REQUEST['id'])?'"options"=>[$_REQUEST["id"]=>["selected"=>true]]':'',
'prompt' => 'Select ',
'onChange' => '$.get("'.Yii::$app->urlManager->createUrl('data/datalist?id=').'"+$(this).val(),function(data){$("#dashboard-id").html(data);})',
])
?>
you have done the mistake in options.Try like below:
<?= $form->field($model, 'id')->dropDownList(ArrayHelper::map($model,'id','name'),
[
'options'=>isset($_REQUEST['id'])?[$_REQUEST["id"]=>["selected"=>true]]:'',
'prompt' => 'Select ',
'onChange' => '$.get("'.Yii::$app->urlManager->createUrl('data/datalist?id=').'"+$(this).val(),function(data){$("#dashboard-id").html(data);})',
])
?>

Yii2 GridView - attribute format based on value of other attribute

I made custom currency formatter + converter based on values from database.
This is how I use it in DetailView
use yii\helpers\Html;
use app\commands\AppHelper;
use yii\widgets\DetailView;
use app\models\Part;
<?= DetailView::widget([
'model' => $model,
'attributes' => [
// ...
[
'attribute' => 'price',
'label' => (new Part())->getAttributeLabel('price_user'),
'format' => [
'currency',
AppHelper::getUserCurrencyCode(),
[
'convert' => true,
'currencyFrom' => $model->currency->code,
'currencyTo' => AppHelper::getUserCurrencyCode(),
],
],
],
// ...
],
]) ?>
In this widget I can accomplish behaviour like this: when there is numeric value, it gets formatted, if there is NULL value, usual (not-set) is printed out...
Notice $model->currency->code which is data from relation, in DetailView easily accessible but I can not figure out how to get that data into formatter in GridView.
Problem is when I want to format data in GridView.
I allow NULL values on column that I need to use formatter on, so I already threw away idea of using
'value' => function ($data, $key, $index, $column) { return $data->value; }
because when NULL value is present, yii sends data like this
<span class="not-set">(not set)</span>
and either I want to let it be or set my custom value (considering different value for other columns with NULL value) and I also want to save trouble handling all those (not set) values.
Another reason is, as I noticed, that if I use 'format' => ... in attribute params, formatting happens before setting those (not set) values.
So I was thinking about somehow passing that $model->currency->code, which is data from relation, to that formatter.
Any ideas? Thanks.
Worst case scenario I will use formatter in value dumping values that contains '<span' or NULL like this, but it is ugly and I dont like it...
EDIT: I added custom static method to format unset data. I still dont like it, but hey, it works ... :D
use yii\helpers\Html;
use app\commands\AppHelper;
use yii\grid\GridView;
use app\models\Part;
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
// ...
[
'attribute' => 'price',
'label' => (new Part())->getAttributeLabel('price_user'),
'value' => function ($data, $key, $index, $column) {
return Part::requestPrice(Yii::$app->formatter->asCurrency(
$data->price,
AppHelper::getUserCurrencyCode(),
[
'precision' => 2,
'convert' => true,
'currencyFrom' => $data->currencyCode,
'currencyTo' => AppHelper::getUserCurrencyCode(),
]));
},
'format' => 'raw',
],
// ...
],
]); ?>
and in Part.php (Part model) I added method
public static function requestPrice($price)
{
if (strpos($price, 'class') !== false || empty($price) || floatval($price) == 0)
return '<span class="not-set">' . Yii::t('app', 'na vyĹžiadanie') . '</span>';
else
return $price;
}

How to preselect/check a default radio button in yii2 RadioList()?

I want the radio button preselected in my form.
<?= $form->field($model, 'config')->radioList(['1'=>'Automatic Entry',2=>'Manual Entry'])
->label('Barcode/Book No Generation'); ?>
The preselected values are taken from $model->config. That means that you should set that attribute to the value that you want preselected :
$model->config = '1';
$form->field($model, 'config')->radioList([
'1' => 'Automatic Entry',
'2' => 'Manual Entry',
]);
The relevant doc for this is in the ActiveForm class.
if you want to use default value of radio, you can use following codes:
<?php $model->isNewRecord==1 ? $model->config=1:$model->config;?>
<?= $form->field($model, 'config')->radioList(
[
'1'=>'Automatic Entry',
'2'=>'Manual Entry'
])->label('Barcode/Book No Generation');
?>
You have to set 'config' attribute.
$model->config = 1;
You'll have first radio button selected when form is loaded.
tarleb is right.
Long shot in the dark since I'm not awfully familiar with yii2, but based on the documentation you should be able to do something like this.
$form->field($model, 'config')->radioList([
'1'=>'Automatic Entry',
'2'=>'Manual Entry',
], [
'item' => function ($index, $label, $name, $checked, $value) {
return Html::radio($name, $checked, ['value' => $value]);
},
]);
// [...]
ActiveForm::end();

Yii2 - jui datepicker extension - display current timestamp by default

i'm using Yii2 extension - Jui DatePicker.
Is there a way to show by default the current timestamp in the text box, so the user does not need to input it every time it fills de form fields?
My view, and the form in Yii2:
<?= $form->field($model, 'data')->widget(DatePicker::className(),
[
'language' => 'en',
'inline' => false,
'clientOptions' =>[
'dateFormat' => 'yyyy-MM-dd',
'showAnim'=>'fold',
'yearRange' => 'c-25:c+0',
'changeMonth'=> true,
'changeYear'=> true,
'autoSize'=>true,
'showOn'=> "button",
'buttonText' => 'clique aqui',
//'buttonImage'=> "images/calendar.gif",
]])
?>
In Yii1 i used to write the code like this (inside the widget), and the timestamp appeared by default:
'htmlOptions'=>array('size'=>12, 'value'=>CTimestamp::formatDate('d/m/Y')),
Is there an equivalent in Yii2?
Many thanks...
You can still use value:
<?= $form->field($model, 'data')->widget(DatePicker::className(),
[
'language' => 'en',
...
'value' => date('Y-m-d'),
As noted in a comment (haven't confirmed this)
'value' => date('Y-m-d') parameter will work only if widget is used without model: DataPicker::widget(['value' => date('Y-m-d')])
Therefore you can use clientOptions to set defaultDate :
'clientOptions' => ['defaultDate' => date('Y-m-d')]
Or better yet you can set $model->data to a default value of the current timestamp, either in your view or in the model.
if (!$model->data) $model->data = date('Y-m-d');

Categories