我是Yii的新手,我正试图以“正确”的方式完成我的初始项目。我创建了一个CFormModel类,它需要三个字段来查询一些数据,一个CForm配置来构造表单,一个CController将它们绑定在一起(所有这些都在下面给出)。
数据请求需要一个帐户,这可能来自几个不同的地方。我认为检索它应该在控制器中。但是,我不知道如何从控制器进入表单的隐藏“帐户”字段,以便它在提交后进入分配给CFormModel的参数。更一般地说,我知道如何从CController传递到查看脚本,但不知道如何传递给CForm。注册表(Yii::app()->params[]
)是我最好的选择吗?
我想我可以将它从表单(和必填字段)中删除,然后等待在提交操作(actionSummaries
)中填充它。这是否打破了CForm的意图?有最好的做法吗?即使采用这种解决方案,有人可以解决第一个问题,以防再次出现吗?
欢迎任何其他温和的批评。
模型/ SummariesForm.php
class SummariesForm extends CFormModel
{
public $account;
public $userToken;
public $year;
public function rules () {...}
public function fetchSummary () {...}
static public function getYearOptions () {...}
}
视图/帐户/ select.php
<?php
$this->pageTitle=Yii::app()->name;
?>
<div class="form">
<?php echo $form->render(); ?>
</div>
控制器/ AccountController.php
class AccountController extends CController
{
public $layout = 'extranet';
public function actionSelect ()
{
$model = new SummariesForm();
// retrieve account
require_once 'AccountCookie.php';
/*
*
* Here, I insert the account directly into the
* model used to build the form, but $model isn't
* available to selectForm.php. So, it doesn't
* become part of the form, and this $model doesn't
* persist to actionSummaries().
*
*/
$model->account = AccountCookie::decrypt();
if ($model->account === false) {
throw new Exception('Unable to retrieve account.');
}
$form = new CForm('application.views.account.selectForm', $model);
$this->render('select', array(
'form' => $form,
'account' => $model->account,
));
}
public function actionSummaries ()
{
$model = new SummariesForm();
if (isset($_POST['SummariesForm'])) {
$model->attributes = $_POST['SummariesForm'];
/*
*
* Should I just omit "account" from the form altogether
* and fetch it here? Does that break the "model"?
*
*/
if ($model->validate() === true) {
try {
$summaries = $model->fetchSummary();
} catch (Exception $e) {
...
CApplication::end();
}
if (count($summaries) === 0) {
$this->render('nodata');
CApplication::end();
}
$this->render('summaries', array('model' => $model, 'summaries' => $summaries));
} else {
throw new Exception('Invalid year.');
}
}
}
}
视图/帐户/ selectForm.php
<?php
return array(
'title' => 'Select year',
'action' => Yii::app()->createUrl('Account/Summaries'),
'method' => 'post',
'elements' => array(
'account' => array(
'type' => 'hidden',
'value' => $account,
),
'userToken' => array(
'type' => 'hidden',
'value' => /* get token */,
),
'year' => array(
'type' => 'dropdownlist',
'items' => SummariesForm::getYearOptions(),
),
),
'buttons' => array(
'view' => array(
'type' => 'submit',
'label' => 'View summaries',
),
),
);
答案 0 :(得分:1)
答案是否定的。从控制器传递到视图时,您可以看到$form
变量几乎像数组一样。解决方案是在$account
中添加更多属性selectForm model
,并将其视为其他元素。如果你想提交它的价值,我不认为将新字段留在表格之外。
编辑: