Timezone for Formatter

To set the default timezone in YII, use the following code in your main config file:

  1. return [  
  2.   'timeZone' => 'America/Phoenix',
  3.  ]

However, take note that YII assumes the datetime in the database is UTC. So, if you are inserting the data in the database already adjusted to current timezone, YII will adjust it again and it will be off.

One option is to set the YII timezone to UTC so that it does not adjust the time.

  1. return [  
  2.   'timeZone' => 'UTC',
  3.  ]

So now you set the default time zone, yet your GridView and DetailView don’t show in the updated time zone. Simple fix. Set the format of the item to datetime. So like ‘last_viewed:datetime’.

Query sum of database column using Active Record

You can use YII2 Active Record to query the sum of a database column.

Here is an example that gets total cost and total revenue for a given date range with status as CREDITED:

  1. $query = Ledger::find();
  2. $this->load($params);
  3.  
  4. $query->where(['status' => 'CREDITED']);
  5. $query->andWhere('date_created >= :begin_date',[':begin_date' => $this->begin_date]);
  6. $query->andWhere('date_created <= :end_date',[':end_date' => $this->end_date]);
  7. $cost = $query->sum('cost');
  8. $revenue = $query->sum('revenue');

Format GridView Footer as Currency

You can use YII2’s built in formatter to format any arbitrary value you like. For example, you may want to format the footer of a grid view as currency. When specifying the cell, you can set the format of that cell. However, while you can control what will be in the footer for that column, GridView does not have a method of formatting the footer values.

Here is a simple method to format any value.

  1. $formatter = new \yii\i18n\Formatter;
  2. $formatted_value = $formatter->asCurrency($value);

and Where greater than less than

When setting up an ActiveDataProvider in search function, you may need to pass a value and have it evaluated and less then (<) or greater than (>). I did not find this info straight forward. But, it is not hard.

Here is an example:

  1. $query->andWhere('table_name.date_created >= :date_val',[':date_val' => $_GET['date_val']);

This utilizes parameter binding, so it is safe to pass the $_GET parameter into it.

You will not need to use ‘table_name’ if you are not using a join clause.

More likely, you will use something like $this->date_val or $this->getAttribute(‘date_val’) rather than $_GET[‘date_val’].