Presentation Of Data

Hi guys.

Suppose we have a model which data is not human-readable (timestamps instead of dates and so on).

So we need to convert it to readable form.

How do you prefer to implement it?

Use a formatter in the views. I use this for data that is stored in a different format for computational reasons (monetary values) but needs to be formatted for display (3000 vs 30,00).

This is trivial in grids/list views and other widgets and adds a bit of code in active forms, where you need to override the attribute’s value by specifying the ‘value’ option.

I was considering formatting the whole model before passing it to the view but there are cases where you display same value in the views with slightly different formatting. And also this is the presentation layer and that’s what for formatters are.

Yeah, I know :(

Actually, the whole thing started when I was working with dates/datetimes heavily. So I had a lot of datepickers in the views (human readable format) and they must be converted to DB format (timestamp w/timezone) on saving. It seemed logical to me to create virtual attributes (created, updated) and setters that converts value to timestamp and sets actual field value (created_at, updated_at).

So the form field was created upon virtual attribute, and the getter was required also. It was way more convenient to have getters/setters instead of afterFind/beforeSave.

Then I started to overuse these things probably. Import CSV? no problem, just create a dozen of setters that convert the values.

User submits site URL? okay, let’s use a setter to remove ‘http(s)://’ part (also I had used custom validators for this, wait, WAT?!). And when we have setter, there’s always getter…

Bad thing is I lose all this stuff when it comes to DAO queries. No AR, no getters. Seems like one layer is missing (between DB and AR probably).

And yes, it’s presentational logic :(

Ok, so how would you implement this: user can submit form that has human-readable data (date, time, phone) that must be stored in another format?


is only for displaying, right? the storage logic must be somewhere else.

Even when using a formatter you’d have to store the raw values somewhere and pass them to a formatter, either manually or through a widget (like grid). So why not just populate a model with values obtained using DAO.

I’d have a model for the form and do as I said before, filter data using filters in validation rules or standalone and format it in the view when drawing the form.

As I said, I filter data using filters in validation rules. I do think about extracting it from there and calling it once just after assigning POST data, like the load() method from Yii2.

ok thx