Hello Model

现在我们来创建model.

model有两个属性 _id and _data. _id存贮id,_data存储greeting数据.

构造器中首先从request中取得id

/**
 * Constructor that retrieves the ID from the request
 *
 * @access    public
 * @return    void
 */
function __construct()
{
    parent::__construct();

    $array = JRequest::getVar('cid',  0, '', 'array');
    $this->setId((int)$array[0]);
}

JRequest::getVar() 方法用来从request中获取数据。第一个参数是form变量的名称,第二个参数是参数默认值,第三个参数he name of the hash to retrieve the value from,第四个是数据类型。

构造器将取得cid数组中的第一个值并赋给id.

setId()被用来设置id,如果id变化了,那么对应的data也应该变化,否则就出错了,因此当我们设置id的值的时候,清空data的数据。
 

/**
 * Method to set the hello identifier
 *
 * @access    public
 * @param    int Hello identifier
 * @return    void
 */
function setId($id)
{
    // Set id and wipe data
    $this->_id        = $id;
    $this->_data    = null;
}

最后还要有getData()来获取数据,getData检查 data是否已经设置,如果已经设置,仅仅返回,如果没有,就从数据库载入。


/**
 * Method to get a hello
 * @return object with data
 */

function &getData()
{
    // Load the data
    if (empty( $this->_data )) {
        $query = ' SELECT * FROM #__hello '.
                '  WHERE id = '.$this->_id;
        $this->_db->setQuery( $query );
        $this->_data = $this->_db->loadObject();
    }
    if (!$this->_data) {
        $this->_data = new stdClass();
        $this->_data->id = 0;
        $this->_data->greeting = null;
    }
    return $this->_data;
}


表单 Form
以下是表单的代码清单:

<?php defined('_JEXEC') or die('Restricted access'); ?>

<form action="index.php" method="post" name="adminForm" />
            </td>
        </tr>
    </table>
    </fieldset>
</div>

<div class="clr"></div>

<input type="hidden" name="option" value="com_hello" />
<input type="hidden" name="id" value="<?php echo $this->hello->id; ?>" />
<input type="hidden" name="task" value="" />
<input type="hidden" name="controller" value="hello" />
</form>

注意,有一个id隐藏项,我们不应该改变id,而仅仅是传递。

相关文章:

  • 2021-05-23
  • 2021-09-25
  • 2021-11-01
  • 2021-07-08
  • 2021-06-04
  • 2022-03-08
  • 2022-02-06
  • 2021-10-01
猜你喜欢
  • 2022-01-16
  • 2021-07-16
  • 2021-10-14
  • 2021-08-15
  • 2021-09-14
  • 2021-10-13
  • 2021-05-28
相关资源
相似解决方案