如何在Cakephp中定义一个复选框变量

时间:2013-03-05 13:48:56

标签: cakephp

我的插件元素中有一个表单,我希望将复选框值插入名为it_queries和字段status_type的表中,它给我一个错误未定义的变量:variableValue [APP \ Plugin \ Feedback \ View \ Elements \ comment_add.ctp,第37行]。我已经在我的控制器中声明了这个变量

$this->set('variableValueStatus', 'Pending');

这是第37行给出了错误

以下是控制器代码

    App::uses('FeedbackAppController', 'Feedback.Controller');

class CommentsController extends FeedbackAppController
{
public $components = array('Feedback.Comments');

public function add($foreign_model = null, $foreign_id = null)
{
if (empty($foreign_model) ||
empty($foreign_id) ||
!$this->request->is('post')
)
{
foreach ($_POST['likebutton'] as $pageId => $likeFlag) {
$dbFlag = $likeFlag ? 'Yes' : 'No';
}
return $this->redirect('/');
}

App::uses($foreign_model, 'Model');
$Model = ClassRegistry::init($foreign_model);

if (!($Model instanceof Model))
{
return $this->redirect('/');
}

if ($Model->hasAny(array($Model->primaryKey => $foreign_id)) == false)
{
return $this->redirect('/');
}

if (!isset($this->request->data['Comment']['foreign_model']) ||
!isset($this->request->data['Comment']['foreign_id']) ||
$this->request->data['Comment']['foreign_model'] != $foreign_model ||
$this->request->data['Comment']['foreign_id'] != $foreign_id)
{
return $this->redirect('/');
}

$user_id = null;

if (isset($this->Auth))
{
$user_id = $this->Auth->user('id');
}

$this->request->data['Comment']['foreign_model'] = $Model->name;
$this->request->data['Comment']['foreign_id'] = $foreign_id;
$this->request->data['Comment']['user_id'] = $user_id;


$this->Comment->create();

if (!$this->Comment->save($this->request->data))
{
$this->set('validation_errors', $this->Comment->validationErrors);
return;
}

$this->redirect($this->request->referer().'#comment-'.$this->Comment->id);
}
}

在我的元素的添加视图中,这是我试图访问变量值

的方式
echo $this->Form->checkbox('ItQuery.status_type', array('type' => 'hidden', 'value'=>$variableValueStatus));

如果有人可以告诉我如何解决这个问题,那就太棒了

1 个答案:

答案 0 :(得分:0)

您只传递变量!post并且如果未设置外部模型和外部ID。 在大多数情况下,这很可能不起作用。 如果在使用变量之前未在视图中对其进行检查,则应始终传递变量。

但无论如何,它仍然是错的。如果你不希望你的表单回到POST上的旧值(它不应该),你将不得不使用“默认”而不是“值”。

此外,最好使用$ this-> request->数据来正确填写默认值的表单:

if (!$this->request->is('post')) {
    $this->request->data['ItQuery']['status_type'] = 'Pending';
}

请参阅working-with-forms