filter dates. Cakephp is returning an array instea

2019-07-18 16:06发布

问题:

I'm building a filter for some paginated lists, and i want to be able to show the elements created between two dates. But I'm not sure how to do it correctly.

The view:

<?php echo $this->Form->create('Logs');?>
<fieldset>
<?php
    echo $this->Form->input('start',array('type'=>'date'));
    echo $this->Form->input('end',array('type'=>'date'));
?>
</fieldset>
<?php echo $this->Form->end('Filter');?>

The controller:

...
$conditions['Logs.created BETWEEN ? AND ?'] = array( $this->data['Logs']['start'],$this->data['Logs']['end']);
...

the problem is that $this->data['Logs']['start'] and $this->data['Logs']['end'] are arrays and i need strings:

[Logs] => Array
(
    [start] => Array
        (
            [month] => 04
            [day] => 19
            [year] => 2011
        )

    [end] => Array
        (
            [month] => 04
            [day] => 19
            [year] => 2011
        )
)

I know that i could use some php functions to transform the array into string, but there must be some function or something in cake. I feel that i'm not constructing the view correctly

Thanks for your help.

回答1:

I think the best bet for you would be to write your own helper function and call it in your controller.

This thread talks about how to create your helper : How best to convert CakePHP date picker form data to a PHP DateTime object?

You can load it into the controller like so

App::import('Helper', 'DateHelper');
$dateHelper = new DateHelper();

Also, why not just switch to a regular text input and maybe a JS datepicker? This would solve your problems without having to resort to the helper route. You'd lose the dropdown availability though.



回答2:

you can use the time helper, and it's daysAsSql function

daysAsSql( $begin, $end, $fieldName, $userOffset = NULL )

daysAsSql returns a string in the format "($field_name >= '2008-01-21 00:00:00') AND ($field_name <= '2008-01-25 23:59:59')". This is handy if you need to search for records between two dates inclusively.

See Time helper