在CakePHP中,如何创建表单以列出日期范围内的模型?
I have a very simple model that includes the auto-filled field much like 'created'. (DateTime format).
I'd like to use the Form helpers if possible, to validate the date fields and whatnot.
I'd like a simple form with a "Begin Date" (YMD, 12 hours), and an "End Date" (same format).
There is already a controller action set up as follows:
function view_between($start_date = null, $end_date = null) {
// ... stuff that works correctly when the URL is manually entered.
}
Have I defined the controller wrong, or how can I pass these values into that function?
The reason I'm stuck is because I tried adding a $form->input('my_datetime_field' ...)
twice, but obviously the name/id were the same on the respective elements.
I have also tried using $form->dateTime(...)
with similar results.
I'm not sure how to uniquely identify a Begin and End date selection, when it should interact with a single field.
Am I going about this wrong? A kind shove in the right direction should suffice.
To specify multiple form elements with the same field name, use this syntax:
$form->input('Modelname.0.fieldname');
$form->input('Modelname.1.fieldname');
Which should return you an array of values to use.
From: http://book.cakephp.org/view/547/Field-naming-convention
You can do an onsubmit that forms a get request that appends start/end dates:
echo $form->create('Foos', array('onsubmit'='submitDates(this)'));
javascript:
function submitDates(frm) {
// grab dates from inputs, form get string and submit to form.action
// get should be something like /controller/view_between/YYYY-MM-DD/YYYY-MM-DD
}
When submitting a FORM, you can only submit it as GET or POST request.
A GET request will attach all form elements to the URL in a format like this:
/controller/action?data[Model][field]=value&data[Model][field2]=value
That doesn't correspond to Cake URL standards, so you'll have to do some URL rewriting or parsing anyway.
A POST request is just that, the data will end up in $this->data
in your controller as usual.
Either way, you can't directly feed a form request into a function with parameters. You could use Javascript, but I suggest you shouldn't. The best is probably a usual POST request. You just need to rewrite your controller action to get the data from $this->data
. Name the form fields whatever you want, just make sure you use them correctly in your controller action.