我的控制器(管理员)中有这个代码:
function save(){
$model = $this->getModel('mymodel');
if ($model->store($post)) {
$msg = JText::_( 'Yes!' );
} else {
$msg = JText::_( 'Error :(' );
}
$link = 'index.php?option=com_mycomponent&view=myview';
$this->setRedirect($link, $msg);
}
Run Code Online (Sandbox Code Playgroud)
在模型我有:
function store(){
$row =& $this->getTable();
$data = JRequest::get('post');
if(strlen($data['fl'])!=0){
return false;
}
[...]
Run Code Online (Sandbox Code Playgroud)
这是有效的 - 生成错误消息,但它返回到项目列表视图.我想留在编辑视图中输入数据.怎么做?
在您的控制器中,您可以:
if ($model->store($post)) {
$msg = JText::_( 'Yes!' );
} else {
// stores the data in your session
$app->setUserState('com_mycomponent.edit.mymodel.data', $validData);
// Redirect to the edit view
$msg = JText::_( 'Error :(' );
$this->setError('Save failed', $model->getError()));
$this->setMessage($this->getError(), 'error');
$this->setRedirect(JRoute::_('index.php?option=com_mycomponent&view=myview&id=XX'), false));
}
Run Code Online (Sandbox Code Playgroud)
然后,您将需要从会话加载数据,如:
JFactory::getApplication()->getUserState('com_mycomponent.edit.mymodel.data', array());
Run Code Online (Sandbox Code Playgroud)
通常这会加载到模型中的方法"loadFormData"中.加载数据的位置取决于您如何实现组件.如果您使用Joomla的表单api,则可以将以下方法添加到模型中.
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_mycomponent.edit.mymodel.data', array());
if (empty($data)) {
$data = $this->getItem();
}
return $data;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
但请注意,如果控制器继承自"JControllerForm",Joomla的API已经可以为您完成所有这些,您不需要重写save方法.创建组件的最佳方法是复制Joomla核心组件中的内容,例如com_content