Format date, time, and numbers

Now, let's see how to format the date, time, and numeric fields. Yii2 provides helpers for each of these types.

To format a value, we will use Yii::$app->formatter; this object belongs to the Formatter class located under yiii18n and supports many types of formatting. All the methods used for this purpose start with an as prefix. Therefore, the asDate method will be used to format dates, and the asCurrency method will be used to format currencies.

The first parameter of each formatting method is the value to be formatted and other fields refer to the format to be used and other optional parameters.

Let's change the view content by adding content of the Model that is ready to be saved:

<?php if($modelCanSave) { ?>
<div class="alert alert-success">
    Model ready to be saved!
    <br /><br />
    These are values: <br />
    Floor: <?php echo $model->floor; ?> <br />
    Room Number: <?php echo $model->room_number; ?> <br />
    Has conditioner: <?php echo Yii::$app->formatter->asBoolean($model->has_conditioner); ?> <br />
    Has TV: <?php echo Yii::$app->formatter->asBoolean($model->has_tv); ?> <br />
    Has phone: <?php echo Yii::$app->formatter->asBoolean($model->has_phone); ?> <br />
    Available from (mm/dd/yyyy): <?php echo Yii::$app->formatter->asDate($model->available_from,'php:m/d/Y'); ?> <br />
    Price per day: <?php echo Yii::$app->formatter->asCurrency($model->price_per_day,'EUR'); ?> <br />
    
</div>
<?php } ?>

If $model is ready to be saved, in the box with the green background, we will have the output of each of the fields of Model.

In this example, we have used:

  • The boolean formatter for has_condition, has_tv, and has_phone members uses the default representation of false and true values; defaults are No for false and Yes for true, but we can change this behavior setting in the $booleanFormat member of Yii::$app->formatter
  • The date formatter for available_from member takes the date format to be used as the second parameter; this date format can be represented with PHP date function style or ICU standard
  • The currency formatter for the price_per_day member is the second parameter with three characters type of currency to be used

This is how the box with the content of Model appears:

Format date, time, and numbers

Show summary of Model content when validation is successful

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.166.98