2012-01-10 60 views
2

我有这样的代码在我的控制器(管理员):如何返回编辑形式?

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); 
} 

在模型中,我有:

function store(){ 
     $row =& $this->getTable(); 

     $data = JRequest::get('post'); 
     if(strlen($data['fl'])!=0){ 
      return false; 
     } 

     [...] 

而且这是工作 - 产生错误信息,但返回的项目列表视图。我想用输入的数据留在编辑视图中。怎么做?

回答

5

在你的控制器,你可以:

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)); 
} 

那么,你需要的东西,如加载从会话的数据:

JFactory::getApplication()->getUserState('com_mycomponent.edit.mymodel.data', array()); 

通常这是在方法“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; 
} 

编辑:

但请注意,Joomla的API已经可以做到这一切你,如果你从控制器“JControllerForm”继承,你不需要重写保存方法。创建组件的最佳方式是复制Joomla核心组件中的内容,例如com_content

0

不建议重写save或任何方法。

如果你真的想覆盖的东西,想前或保存后,系统应该使用JTable文件更新的东西。

例如:

/** 
* Example table 
*/ 
class HelloworldTableExample extends JTable 
{ 
    /** 
    * Method to store a node in the database table. 
    * 
    * @param boolean $updateNulls True to update fields even if they are null. 
    * 
    * @return boolean True on success. 
    */ 
    public function store($updateNulls = false) 
    { 
     // This change is before save 
     $this->name = str_replace(' ', '_', $this->name); 

     if (!parent::store($updateNulls)) 
     { 
      return false; 
     } 

     // This function will be called after saving table 
     AnotherClass::functionIsCallingAfterSaving(); 
    } 
} 

您是否可以extends使用JTable类的任何方法,这就是推荐的方法做。