J3.x

建立一個簡單的模組/新增表單欄位

From Joomla! Documentation

< J3.x:Creating a simple module
This page is a translated version of the page J3.x:Creating a simple module/Adding Form Fields and the translation is 50% complete.
Other languages:
Bahasa Indonesia • ‎Deutsch • ‎English • ‎Nederlands • ‎español • ‎français • ‎português • ‎русский • ‎中文(台灣)‎
Joomla! 
3.x
教學
建立一個簡單的模組

這一系列的文章介紹如何 建立一個 Joomla! 模組 版本 Joomla 3.x。您可以依序瀏覽文章。

讓我們從簡介開始,您可以使用底下的導覽按鈕來瀏覽文章,或是右側的方塊中的連結(列出所有的文章)。 您可以觀看 2 部和本教學相關的影片,基本 Joomla 模組開發影片教學 1 and 基本 Joomla 模組開發影片教學 2.




Form fields give a great deal of customisation in Joomla and for modules are the sole way of allowing the user to tweak the module to the needs of their site.

新增表單欄位到模組

In this case we are going to extend our previous example using the database to provide a list of languages for the user to select from. To allow this to happen we will use the SQL form field type. (The full details for this is on the SQL Form Field docs page).

First of all we are going to add a form field into our .xml file. Remember those config tags that we added in earlier? Now inside these tags we are going to add the following code:

<fields name="params">
    <fieldset name="basic">
        <field
               name="lang"
               type="sql"
               default="1"
               label="Select a language"
               query="SELECT id AS value, lang FROM #__helloworld" />
    </fieldset>
</fields>

This selects the languages from the database table and allows the user to choose one from a select element.

If you were to install the module as it is now you would see if you were to access the module in the backend of Joomla that a dropdown has appeared (although picking an option won't affect the module at the moment).

Note: The form field parameters are stored for each module in the #__modules table under the params field as JSON-encoded string.

現在我們來讓表單欄位作些事情吧!Ω

Go into the mod_helloworld.php file and retrieve the parameter. (Note that you cannot retrieve the parameter in the helper.) Then pass it into the helper function.

/**
  * This retrieves the lang parameter we stored earlier. Note the second part
  * which assigns the default value of 1 if the parameter cannot be
  * retrieved for some reason.
**/
$language = $params->get('lang', '1');
$hello    = modHelloWorldHelper::getHello( $language );

Now let's edit our database query in the helper file to reflect our parameter choice.

// Obtain a database connection.
$db = JFactory::getDbo();
// Retrieve the shout. Note that we are now retrieving the id not the lang field.
$query = $db->getQuery(true)
            ->select($db->quoteName('hello'))
            ->from($db->quoteName('#__helloworld'))
            ->where('id = '. $db->Quote($params));
// Prepare the query
$db->setQuery($query);
// Load the row.
$result = $db->loadResult();
// Return the Hello.
return $result;

結論

表單欄位給用戶方便的途徑來為他們的網站模組客製化。這會讓模組使用的範圍更廣。