Formatted date filter in CGridView - yii

I display my date in CGridView as: "22.6.2012 22:53" with:
array('name' => 'date',
'value' => date("j.n.Y G:i", strtotime($model->date))
),
But in my filter, I need to search in this format (which is in the database) to get results: "2012-06-22 22:53".
How can I make my filter to work in the format that is displayed in my CGridView? I've searched for an answer but haven't found one, I've also tried adding the date function in my model search() for this attribute:
$criteria->compare('date', date("j.n.Y G:i", strtotime($this->date), true);
but then I just get an empty list :)
Help would be greatly appreciated.

To begin with, you should not be using the value property to control the formatting of dates. The proper way is to set the type property to 'date' and, if you do not do this already, set CApplication.language to target the appropriate locale.
For the filter it would be best for the user if you use a CJuiDatePicker widget to let the user visually pick the date; there's a short and to-the-point guide on how to do that here.
Update:
Formatting columns with type == 'date' is done through CGridView.formatter, for which if you do not explicitly set a value the default is whatever the 'format' application component is. So you can specify and configure a CFormatter on the spot, or if you want to use the application's formatter but with slight modifications you can do
$formatter = clone Yii::app()->format;
$formatter->dateFormat = 'whatever'; // or $formatter->dateTimeFormat
and then assign this instance to CGridView.formatter.

compare() makes a sql sentence with the input, so I had to change the input to my wanted format.
my function:
function changeDateToDBformat($datum) {
if (strstr($datum, '.') || strstr($datum, ':')) {
$formats = array('!j.n', '!j.n.Y', '!j.n.Y H:i', '!n.Y H:i', '!n.Y', '!H:i', '!j.n.Y H', '!n.Y H', '!Y H:i', '!Y H');
$date = false;
foreach ($formats as $format) {
$date = DateTime::createFromFormat($format, $datum);
if (!($date === false)) {
$izbraniFormat = $format;
break;
}
}
if (!$date === false) {
$datum1 = $date->format('Y-m-d H:i');
$date2 = DateTime::createFromFormat(substr($izbraniFormat, 1, strlen($izbraniFormat)), $datum);
$datum2 = $date2->format('Y-m-d H:i');
$datumcas1 = explode(' ', $datum1);
$datumcas2 = explode(' ', $datum2);
$prvidatum = explode('-', $datumcas1[0]);
$drugidatum = explode('-', $datumcas2[0]);
$koncniDatum = '';
for ($a = 0; $a < sizeof($prvidatum); $a++) {
if ($prvidatum[$a] == $drugidatum[$a])
$koncniDatum .= '-' . $prvidatum[$a];
}
$koncniCas = '';
$prvicas = explode('-', $datumcas1[1]);
$drugicas = explode('-', $datumcas2[1]);
for ($a = 0; $a < sizeof($prvicas); $a++) {
if ($prvicas[$a] == $drugicas[$a])
$koncniCas .= ':' . $prvicas[$a];
}
$koncniDatum = substr($koncniDatum, 1, strlen($koncniDatum));
if (strlen($koncniCas) > 0)
$koncniDatum .= ' ' . substr($koncniCas, 1, strlen($koncniCas));
$datum = $koncniDatum;
}
}
return $datum;
}
//translations:
//izbrani == selected
//datum == date
//cas == time
//koncni == end
//prvi == first
//drugi == second
With this, a user can enter date in the format "j.n.Y H:i" and also just portions of this format (j.n, n.Y, Y H:i,...).
I would like to thank Jon and nickb for help! link

Like many others I also struggled with this, well displaying the grid wasn't the problem, but filtering in the localized datetime was!
So I created my own formatter, used it in the search() function of my models (when passing the search parameters to compare()) and it works like a charm.
I can now filter on date/datetime fields in any localization (I use Dutch):
"30-12-2018" becomes "2018-12-30"
">30-12-2018" becomes ">2018-12-30"
"30-12-2018 23:59:49" becomes "2018-12-30 23:59:49"
">=30-12-2018 23:59:49" becomes ">=2018-12-30 23:59:49"
My localization:
// dateFormat['short'] = 'dd-MM-yyyy'
// timeFormat['medium'] = 'HH:mm:ss'
Yii::app()->format->datetimeFormat = strtr(Yii::app()->locale->dateTimeFormat,
array("{0}" => Yii::app()->locale->getTimeFormat('medium'),
"{1}" => Yii::app()->locale->getDateFormat('short')));
Yii::app()->format->dateFormat = 'short';
Yii::app()->format->timeFormat = 'medium';
My CGridView contains the following date time column:
'mutation_date_time:dateTime'
And (a snippet of) my own formatter with some handy functions:
class Formatter extends CLocalizedFormatter
{
public function formatWithoutSearchOperator($value)
{
// This snippet is taken from CDbCriteria->compare()
if(preg_match('/^(?:\s*(<>|<=|>=|<|>|=))?(.*)$/',$value,$matches))
{
$value=$matches[2];
$op=$matches[1];
}
else
$op='';
return $value;
}
public function formatOnlySearchOperator($value)
{
// This snippet is taken from CDbCriteria->compare()
if(preg_match('/^(?:\s*(<>|<=|>=|<|>|=))?(.*)$/',$value,$matches))
{
$value=$matches[2];
$op=$matches[1];
}
else
$op='';
return $op;
}
/*
* Format a localized datetime back to a database datetime (Y-m-d H:i:s).
* If a comparison operator is given, it is preserved. So strip it if you need to save the date in the database.
* If no time given, it's also not returned (MySQL database appends '00:00:00' as time to it upon saving).
* With this function the following localized datetimes just work like the stock datetime filters:
* - "30-12-2018" becomes "2018-12-30"
* - "30-12-2018 " becomes "1970-01-01" (note the extra space in input)
* - ">30-12-2018" becomes ">2018-12-30"
* - "30-12-2018 23:59:49" becomes "2018-12-30 23:59:49"
* - ">=30-12-2018 23:59:49" becomes ">=2018-12-30 23:59:49"
*
* For save() and afterFind() integration see:
* https://github.com/YetOpen/i18n-datetime-behavior
*/
public function formatToDatabaseDatetime($value)
{
// get the comparison operator from the string:
$comparator = $this->onlySearchOperator($value);
// get the datetime without the comparison operator:
$datetime = $this->withoutSearchOperator($value);
// parse the given datetime according to the locale format to a timestamp
$datetime_parsed = CDateTimeParser::parse(
$datetime,
strtr(
Yii::app()->locale->datetimeFormat,
array(
"{0}" => Yii::app()->locale->getTimeFormat(Yii::app()->format->timeFormat),
"{1}" => Yii::app()->locale->getDateFormat(Yii::app()->format->dateFormat)
)
)
);
// if its not a valid date AND time, check if it can be parsed to a date only:
if($datetime_parsed === false)
{
$date_parsed = CDateTimeParser::parse(
$datetime,
Yii::app()->locale->getDateFormat(Yii::app()->format->dateFormat)
);
}
// If no time part given, also output only the date
if($datetime_parsed===false)
{
$transformed = date(
'Y-m-d',
$date_parsed
);
}
else
{
$transformed = date(
'Y-m-d H:i:s',
$datetime_parsed
);
}
return $comparator . $transformed;
}
}
And within my search() function in my CActiveRecord model I use the following to compare the localized datetime with the records in the database:
$criteria->compare('mutation_date_time',Yii::app()->format->toDatabaseDateTime(trim($this->mutation_date_time)),true);
Please note the trim() there, that's by design (see function description formatToDatabaseDateTime()).
A big difference with filtering directly in correct database format: an invalid date converts to "1970-01-01"!
I highly appreciate feedback and I really hope my code helps somebody!

Related

How to format money on Shopify using JavaScript

I found this Gist for money formatting on Shopify using JavaScript https://gist.github.com/stewartknapman/8d8733ea58d2314c373e94114472d44c
I placed it in my cart page and when I try:
Shopify.formatMoney(2000, '$')
I get this:
cart:2166 Uncaught TypeError: Cannot read property '1' of null
at Object.Shopify.formatMoney (cart:2166)
at <anonymous>:1:9
this is at switch(formatString.match(placeholderRegex)[1]) {
I expect to get $20.00
Do you know where the problem is?
Similar question: Shopify Buy Button Error: "cannot read property '1' of null"
The Gist content
var Shopify = Shopify || {};
// ---------------------------------------------------------------------------
// Money format handler
// ---------------------------------------------------------------------------
Shopify.money_format = "${{amount}}";
Shopify.formatMoney = function(cents, format) {
if (typeof cents == 'string') { cents = cents.replace('.',''); }
var value = '';
var placeholderRegex = /\{\{\s*(\w+)\s*\}\}/;
var formatString = (format || this.money_format);
function defaultOption(opt, def) {
return (typeof opt == 'undefined' ? def : opt);
}
function formatWithDelimiters(number, precision, thousands, decimal) {
precision = defaultOption(precision, 2);
thousands = defaultOption(thousands, ',');
decimal = defaultOption(decimal, '.');
if (isNaN(number) || number == null) { return 0; }
number = (number/100.0).toFixed(precision);
var parts = number.split('.'),
dollars = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + thousands),
cents = parts[1] ? (decimal + parts[1]) : '';
return dollars + cents;
}
switch(formatString.match(placeholderRegex)[1]) {
case 'amount':
value = formatWithDelimiters(cents, 2);
break;
case 'amount_no_decimals':
value = formatWithDelimiters(cents, 0);
break;
case 'amount_with_comma_separator':
value = formatWithDelimiters(cents, 2, '.', ',');
break;
case 'amount_no_decimals_with_comma_separator':
value = formatWithDelimiters(cents, 0, '.', ',');
break;
}
return formatString.replace(placeholderRegex, value);
};
I found formatMoney function in my theme and I was able to call it and it worked.
pipelineVendor.themeCurrency.formatMoney(2000);
result: $20.00
It's probably too late for the original asker, but for anyone else looking for an answer, I believe the correct call for this function is:
Shopify.formatMoney(2000, '${{amount}}')
instead of
Shopify.formatMoney(2000, '$')
based on the comment of the gist author on Github:
It doesn’t actually care what the currency is. The first argument is
the unformatted amount. The second argument is the format, which could
be whatever you need for the currently displayed currency i.e. “£{{
amount }}”. Then pass it a new amount and new format when you change
the currency.

How to test current date condition in behat?

I have feature that is based on current date, and the question is if it is good solution to write if condition in scenario. Simple example: if tested date is equal to current then other field is equal to 0 else equal 10. Meybe there are libraries to mock current date time in symfony 4.
You could write a step like:
Then I should see sysdate with format "Y-m-d" in the "example" field
Then for your context:
public function iShouldSeeSysdateWithFormatInTheField(string $format, string $key)
{
$field = $this->getSession()->getPage()->findField($key);
$value = (new DateTime())->format($format);
if (is_null($field->getValue())) {
assertEmpty($value);
}
if($value != $field->getValue()) {
throw new Exception('date does not match');
}
}

Express Validatior - How Do I Break The Validation Chain?

I have a date field that I want to ensure is in a valid format and if so is the user over 18. The format is YYYY-MM-DD.
Here is one of my validators - the one that is failing:
body('birthday', 'Date format should be: YYYY-MM-DD')
.isRFC3339()
.custom(date => {
const over18 = moment().diff(date, 'years') >= 18;
if(!over18) {
return Promise.reject('You must be 18 or over!');
}
}),
Currently what happens is if the date is not a RFC3339 date the validation chain continues. This is problematic because moment produces an error if I pass an ill formatted date.
How do I break the chain after the call to .isRFC3339() so that if the date is invalid the custom validator will not run? I couldn't find anything in the docs
You can use momentjs strict mode together with String + Format parsing using moment.ISO_8601 (or moment.HTML5_FMT.DATE) special formats.
Your code could be like the following:
body('birthday', 'Date format should be: YYYY-MM-DD')
// .isRFC3339() // no more needed
.custom(date => {
const mDate = moment(date, moment.ISO_8601, true);
const over18 = moment().diff(mDate, 'years') >= 18;
if(!mDate.isValid()) {
return Promise.reject('Date is not YYYY-MM-DD');
if(!over18) {
return Promise.reject('You must be 18 or over!');
}
}),

Sorting dates with moment.js does not work when date is a link

I'm using DataTables 1.10.5. When I'm trying to sort on dates using the recommended moment.js (as per http://datatables.net/blog/2014-12-18), thinks work fine:
http://jsfiddle.net/9gohzd9t/1/
However, when I add a link (a href) to that date, it sorts on the link instead of the date:
http://jsfiddle.net/dnsL2oc4/1/
Any idea on how to properly fix this without too much hacking around?
The problem lies in the unshift method of datetime-moment.js. Moment tries to convert 12-01-2001 to a valid date in the given "DD-MM-YYYY"-Format, which it can't obviously. So you have to strip the html away from the date, probably with a function like this:
function strip(html) {
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
And then strip the string in the unshift method (Replace datetime-moment.js with the code below):
$.fn.dataTable.moment = function (format, locale) {
var types = $.fn.dataTable.ext.type;
// Add type detection
types.detect.unshift(function (d) {
return moment(strip(d), format, locale, true).isValid() ?
'moment-' + format :
null;
});
// Add sorting method - use an integer for the sorting
types.order['moment-' + format + '-pre'] = function (d) {
return moment(strip(d), format, locale, true).unix();
};
};

AgileToolkit - Custom SQL request + Paginator

Hello I a little problem with my paginator, i would like to use some custom SQL Request but each time i click on a paginator link it loads my model without the custom request
I enter informations on a form that I send by GET method:
$view->grid->js()->reload(array("From" =>
$form->get("From"),"To" => $form->get("To"),"SSID" => $form->get("SSID")))
->execute();
On my view I have :
$this->request=$this->api->db->dsql();
$this->grid=$this->add('Grid');
$this->grid->setModel('Systemevents',array('ID','ReceivedAt','Message'));
$this->grid->addPaginator(10);
if (isset($_GET["SSID"])) {
$this->ssid = $_GET["SSID"];
}
if (isset($_GET["From"])) {
$this->from = $_GET["From"];
}
if (isset($_GET["To"])) {
$this->to = $_GET["To"];
}
$this->grid->dq->where($this->requette->expr('Message like "%.% '
. $this->ssid . ' % src=%"'))
->where($this->requette->expr("ReceivedAt >= '".$this->from. "'
AND ReceivedAt <= '".$this->to."'"));
The problem is that the where condition disapear when i change the page with the paginator.
I did not found any solution to my problem so I have done something differently
I added two buttons to my grid wich allows me to change the limit of the sql request.
The previous button is hidden if the limit is 0.
Now i have to found how to count the number of lines (select count('ID') from 'SystemEvents' where....) and to stock it in a variable.
Finally the ultimate solution was to do :
if ((isset($_GET["SSID"])) || (isset($_GET["From"])) || (isset($_GET["To"]))) {
//GET Method from Recherche.php
$this->ssid = ($_GET["SSID"] == "null" ? null : $_GET["SSID"]);
$this->api->stickyGET("SSID"); // the solutiuon is here
$this->from = ($_GET["From"] == "null" ? null : $_GET["From"]);
$this->api->stickyGET("From"); // <===== the solutiuon is here
$this->to = ($_GET["To"] == "null" ? null : $_GET["To"]);
$this->api->stickyGET("To"); // <===== the solutiuon is here
}