如何创建一个MVC模式的Joomla组件教程(十八) - 创建管理员界面 保存记录功能下

在model中实现数据操作

现在添加一个store方法用来保存数据,store要绑定form传递的数据到TableHello对象,检查数据格式是否正确,保存数据。

store方法代码如下:

/**
 * Method to store a record
 *
 * @access    public
 * @return    boolean    True on success
 */
function store()
{
    $row =& $this->getTable();

    $data = JRequest::get( 'post' );
    // Bind the form fields to the hello table
    if (!$row->bind($data)) {
        $this->setError($this->_db->getErrorMsg());
        return false;
    }

    // Make sure the hello record is valid
    if (!$row->check()) {
        $this->setError($this->_db->getErrorMsg());
        return false;
    }

    // Store the web link table to the database
    if (!$row->store()) {
        $this->setError($this->_db->getErrorMsg());
        return false;
    }

    return true;
}

第一行获取了JTable类实例,如果正确命名了名字,我们不必指定名字,Jmodel类自动找到合适的Jtable,我们创建了一个tables目录,并将JTable 命名为TableHello保存在 hello.php文件中,遵循这样的约定,就可以自动创建对象。

第二行我们返回form的数据。JRequest做的非常简单,本例中,我们获取了所有post的变量,这些变量是以数组方式返回的。

其余的非常简单了- bind, check and store. bind() 拷贝form的相应变量到JTable中. 本例中id和greeting赋值到TableHello对象中.

check() 执行数据验证. 在JTable() class, 这个方法仅仅是简单返回true. 尽管现在没有实际用处,但是以后check可以做验证。

store()方法保存数据到数据库中,如果id为0,将创建一个新目录,否则更新记录。


添加controller任务

现在来添加任务,任务的名称是save

以下是代码清单:

/**
 * save a record (and redirect to main page)
 * @return void
 */
function save()
{
    $model = $this->getModel('hello');

    if ($model->store()) {
        $msg = JText::_( 'Greeting Saved!' );
    } else {
        $msg = JText::_( 'Error Saving Greeting' );
    }

    // Check the table in so it can be edited.... we are done with it anyway
    $link = 'index.php?option=com_hello';
    $this->setRedirect($link, $msg);
}

我们所要做的是取得model,调用store方法,然后用 setRedirect(),返回greetings的列表页面,同事返回一个信息,显示在页面的顶部。

posted on 2009-12-26 22:07  14的路  阅读(590)  评论(0编辑  收藏  举报

导航

友情链接:源码下载