J3.x

Difference between revisions of "Developing an MVC Component/Using the database"

From Joomla! Documentation

< J3.x:Developing an MVC Component
m (high lights file name than beginner easily to understand)
(There is no model in backend yet)
 
(33 intermediate revisions by 13 users not shown)
Line 1: Line 1:
{{:J3.3:Developing a MVC Component}}
+
<noinclude><languages /></noinclude>
 +
{{:J3.1:Developing an MVC Component/<translate><!--T:1-->
 +
en</translate>}}
 +
<translate>== Introduction == <!--T:2--></translate>
 +
<translate><!--T:3-->
 +
This tutorial is part of the [[S:MyLanguage/J3.3:Developing an MVC Component | Developing an MVC Component for Joomla! 3.3]] tutorial. You are encouraged to read the previous parts of the tutorial before reading this. Also while doing this part you are also encouraged to read more on database queries, selecting data from a database table and retrieving it in several formats [[S:MyLanguage/Selecting_data_using_JDatabase|here]].</translate>
  
== Introduction ==
+
<translate><!--T:32--> There are also 3 videos associated with this step in the tutorial, covering [https://www.youtube.com/watch?v=JWS_3rx8RzY the Database Setup], [https://www.youtube.com/watch?v=rKEHDeFGlGM Displaying the message (using JTable)] and [https://www.youtube.com/watch?v=uEDNyG6pSEk Admin message selection (and JDatabase)].</translate>
This tutorial is part of the [[J3.3:Developing a MVC Component | Developing a MVC Component for Joomla! 3.3]] tutorial. You are encouraged to read the previous parts of the tutorial before reading this.
 
  
== Using the database ==
+
{{#widget:YouTube|id=JWS_3rx8RzY}}
Components usually manage their contents using the database. During the install/uninstall/update phase of a component, you can execute SQL queries through the use of SQL text files.
 
  
With your favorite file manager and editor create two files called ''admin/sql/install.mysql.utf8.sql'' and ''admin/sql/updates/mysql/0.0.6.sql''. They should both have the same content, as follows:
+
{{#widget:YouTube|id=rKEHDeFGlGM}}
 +
 
 +
{{#widget:YouTube|id=uEDNyG6pSEk}}
 +
 
 +
<translate>== Using the database == <!--T:4--></translate>
 +
<translate><!--T:5-->
 +
Components usually manage their contents using the database. During the install/uninstall/update phase of a component, you can execute SQL queries through the use of SQL text files.</translate>
 +
 
 +
<translate><!--T:6-->
 +
With your favourite file manager and editor create two files called <tt>admin/sql/install.mysql.utf8.sql</tt> and <tt>admin/sql/updates/mysql/0.0.6.sql</tt>. They should both have the same content, as follows:</translate>
  
 
<span id="admin/sql/install.mysql.utf8.sql">
 
<span id="admin/sql/install.mysql.utf8.sql">
'''''admin/sql/install.mysql.utf8.sql'' and ''admin/sql/updates/mysql/0.0.6.sql'''''
+
<tt>'''admin/sql/install.mysql.utf8.sql''' and '''admin/sql/updates/mysql/0.0.6.sql'''</tt>
 
<source lang="sql">
 
<source lang="sql">
 
DROP TABLE IF EXISTS `#__helloworld`;
 
DROP TABLE IF EXISTS `#__helloworld`;
Line 17: Line 29:
 
`id`      INT(11)    NOT NULL AUTO_INCREMENT,
 
`id`      INT(11)    NOT NULL AUTO_INCREMENT,
 
`greeting` VARCHAR(25) NOT NULL,
 
`greeting` VARCHAR(25) NOT NULL,
`published` tinyint(4) NOT NULL,
+
`published` tinyint(4) NOT NULL DEFAULT '1',
 
PRIMARY KEY (`id`)
 
PRIMARY KEY (`id`)
 
)
 
)
Line 31: Line 43:
 
</span>
 
</span>
  
The file ''install.mysql.utf8.sql'' will be executed when you install this component. The file ''0.0.6.sql'' is executed when you do an update.
+
<translate><!--T:43--> '''Note.''' Nowadays Joomla recommends specifying</translate>
  
'''Important Note:''' When the component is installed, the files in the SQL updates folder (for example, ''admin/sql/updates/mysql'') are read and the name of the last file alphabetically is used to populate the component's version number in the <code>#__schemas</code> table. This value must be in this table in order for the automatic update to execute the update SQL files for future versions. For this reason, it is good practice to create a SQL update file for each version (even if it is empty or just has a comment). This way the <code>#__schemas</code> version will always match the component version.
+
<tt>ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci;</tt>
  
'''Important Note:''' When saving the SQL files in utf8, be sure to save them as utf8 NOT BOM or the query will fail with MySQL error #1064.
+
<translate><!--T:44--> instead of what is above. InnoDB is the more modern (and now default) MySQL database engine, replacing MyISAM, and utf8mb4 supports a wider range of character sets including emojis. However, I haven't tested all the steps in the tutorial with this setting, so if you use it and go through the complete tutorial series and find no problems please consider updating this file and where it occurs in other tutorial steps.</translate>
  
This is the install file. It will be executed if you put an appropriate order in the ''helloworld.xml'' file
+
<translate><!--T:45--> Also note that if you look at a Joomla database many of the key database tables have a field called 'title' for the sort of information which we're storing in our 'greeting' field. It's generally advisable to follow the Joomla pattern, and use 'title' as the field name, as when we try to use more complex functionality (such as ACL and associations) some of the core Joomla javascript routines we want to reuse expect a 'title' field to be present. (Something to consider changing when this tutorial series is next updated).</translate>
 +
 
 +
<translate><!--T:46-->
 +
Often you will find that the database table has a field to keep track of the published/unpublished state of an item. Using the name 'state' within Joomla is not recommended as it can lead to conflicts, instead the name 'published' is used.<br />
 +
Note: How to tell Joomla to store the value of the published form field into a different name database field? We do this by using the method [[S:MyLanguage/Column alias|setColumnAlias()]] (since 3.4.0).</translate>
 +
 
 +
<translate><!--T:7-->
 +
The file <tt>install.mysql.utf8.sql</tt> will be executed when you install this component. The file ''0.0.6.sql'' is executed when you do an update.</translate>
 +
 
 +
<translate><!--T:10-->
 +
This is the install file. It will be executed if you put an appropriate order in the <tt>helloworld.xml</tt> file.</translate>
 +
 
 +
<translate><!--T:9-->
 +
'''Important Note:''' When saving the SQL files in utf8, be sure to save them as utf8 NOT BOM or the query will fail with MySQL error #1064.</translate>
  
 
<span id="helloworld.xml">
 
<span id="helloworld.xml">
''helloworld.xml''
+
<tt>'''helloworld.xml'''</tt>
 
<source lang="xml" highlight="13,17-26,58-61">
 
<source lang="xml" highlight="13,17-26,58-61">
 
<?xml version="1.0" encoding="utf-8"?>
 
<?xml version="1.0" encoding="utf-8"?>
<extension type="component" version="3.2.0" method="upgrade">
+
<extension type="component" version="3.0" method="upgrade">
  
 
<name>Hello World!</name>
 
<name>Hello World!</name>
 
<!-- The following elements are optional and free of formatting constraints -->
 
<!-- The following elements are optional and free of formatting constraints -->
<creationDate>January 2014</creationDate>
+
<creationDate>January 2018</creationDate>
 
<author>John Doe</author>
 
<author>John Doe</author>
 
<authorEmail>john.doe@example.org</authorEmail>
 
<authorEmail>john.doe@example.org</authorEmail>
Line 110: Line 135:
 
</span>
 
</span>
  
 +
<translate>
 +
<!--T:40-->
 
Do the same for the uninstall file:
 
Do the same for the uninstall file:
  
With your favorite file manager and editor put a file ''admin/sql/uninstall.mysql.utf8.sql'' containing:
+
<!--T:41-->
 +
With your favourite file manager and editor put a file <tt>admin/sql/uninstall.mysql.utf8.sql</tt> containing:</translate>
  
 
<span id="admin/sql/uninstall.mysql.utf8.sql">
 
<span id="admin/sql/uninstall.mysql.utf8.sql">
''admin/sql/uninstall.mysql.utf8.sql''
+
<tt>'''admin/sql/uninstall.mysql.utf8.sql'''</tt>
 
<source lang="sql">
 
<source lang="sql">
 
DROP TABLE IF EXISTS `#__helloworld`;
 
DROP TABLE IF EXISTS `#__helloworld`;
Line 121: Line 149:
 
</span>
 
</span>
  
== Adding a new field type ==
+
<translate>== Schema Numbering == <!--T:33--> </translate>
For the moment, we have used a [[J3.3:Developing a MVC Component/Adding a menu type to the site part|hard coded field type for messages]]. We need to use our database for choosing the message.
+
 
 +
<translate>
 +
<!--T:34-->
 +
Your component has a version number (which is specified inside the <tt><version></tt> tag in your helloword.xml manifest file), and your component's database schema has its own version number (which is based on the filenames of the sql update files).</translate>
  
Modify the ''site/views/helloworld/tmpl/default.xml'' file and put these lines
+
<translate>
 +
<!--T:35-->
 +
Joomla keeps track of the database schema version of your component through a record in its <tt>#__schemas</tt> table. So when you first install a component, if there's a file called, say, <tt>admin/sql/updates/mysql/0.0.6.sql</tt>, then Joomla will store the value <tt>0.0.6</tt> it its schemas record. </translate>
 +
 
 +
<translate>
 +
<!--T:36-->
 +
When you next install a newer version of this component - it doesn't have to be the next version, you can skip versions - Joomla will do the following:
 +
* it will retrieve the component's latest database schema version from its <tt>#__schemas</tt> table - so it might find in our example the value 0.0.6.
 +
* it will get the filenames of all the files in the <tt>admin/sql/updates/mysql/</tt> directory, and organise them in numerically increasing order.
 +
* it will process in order the update files which have filenames numerically after the current schema version - so it might find files called 0.0.7.sql, 0.0.9.sql and 0.0.10.sql, and process these in order.
 +
* it will update the schemas record to have the number of the last update file which it processed - eg 0.0.10. </translate>
 +
 
 +
<translate>
 +
<!--T:37-->
 +
If you have already released versions of your component when you introduce database use, as we have simulated in this tutorial series, then your first update file must have exactly the same content as the install file.  If you have not, then it should be empty.</translate>
 +
 
 +
<translate>
 +
<!--T:38-->
 +
Although it may be a good idea to keep the two version numbers in step, you don't have to. Joomla takes the schema version from the name of the numerically last update file. That's why it is recommended that there should be an initial update file, even if it's empty. If you want to keep your schema numbers in step with the component version numbers when you update your code but not the database schema, you simply include an update file to go with the new release number, and that update file, too, will be empty.</translate>
 +
 
 +
<translate>
 +
<!--T:39-->
 +
As you make subsequent releases of your component the database install file must always contain the full schema and the update files only need to contain any changes you have made to the schema since the last update.</translate>
 +
 
 +
<translate>
 +
== Adding a new field type == <!--T:13-->
 +
</translate>
 +
<translate><!--T:14-->
 +
For the moment, we have used a [[S:MyLanguage/J3.3:Developing an MVC Component/Adding a menu type to the site part|hard coded field type for messages]]. We need to use our database for choosing the message, and for this we need to define a custom field type (which we call ''helloworld'' below) as described [[S:MyLanguage/Creating_a_custom_form_field_type|here]].</translate>
 +
 
 +
<translate><!--T:15-->
 +
Modify the <tt>site/views/helloworld/tmpl/default.xml</tt> file and put these lines</translate>
  
 
<span id="site/views/helloworld/tmpl/default.xml">
 
<span id="site/views/helloworld/tmpl/default.xml">
''site/views/helloworld/tmpl/default.xml''
+
<tt>'''site/views/helloworld/tmpl/default.xml'''</tt>
 
<source lang="xml" highlight="8,11-16">
 
<source lang="xml" highlight="8,11-16">
 
<?xml version="1.0" encoding="utf-8"?>
 
<?xml version="1.0" encoding="utf-8"?>
Line 151: Line 213:
 
</span>
 
</span>
  
It introduces a new field type and tells Joomla to look for the field definition in the ''/administrator/components/com_helloworld/models/fields'' folder.
+
<translate><!--T:16-->
 +
It introduces a new field type and tells Joomla to look for the field definition in the <tt>/administrator/components/com_helloworld/models/fields</tt> folder.</translate>
  
With your favorite file manager and editor put a file ''admin/models/fields/helloworld.php'' file containing:
+
<translate><!--T:17-->
 +
In order to learn more on database queries, selecting data from a database table and retrieving it in several formats [[S:MyLanguage/Selecting_data_using_JDatabase|click here]].</translate>
 +
<translate><!--T:18-->
 +
With your favourite file manager and editor put a file ''admin/models/fields/helloworld.php'' containing:</translate>
  
 
<span id="admin/models/fields/helloworld.php">
 
<span id="admin/models/fields/helloworld.php">
''admin/models/fields/helloworld.php''
+
<tt>'''admin/models/fields/helloworld.php'''</tt>
 
<source lang="php">
 
<source lang="php">
 
<?php
 
<?php
Line 163: Line 229:
 
  * @subpackage  com_helloworld
 
  * @subpackage  com_helloworld
 
  *
 
  *
  * @copyright  Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
+
  * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 
  * @license    GNU General Public License version 2 or later; see LICENSE.txt
 
  * @license    GNU General Public License version 2 or later; see LICENSE.txt
 
  */
 
  */
Line 218: Line 284:
 
</span>
 
</span>
  
The new field type displays a drop-down list of messages to choose from. You can see the result of this change in the menu manager section for the helloworld item.
+
<translate><!--T:19-->
 +
The new field type displays a drop-down list of messages to choose from. You can see the result of this change in the menu manager section for the helloworld item.</translate>
  
== Display the chosen message ==
+
<translate>
When a menu item of this component is created/updated, Joomla stores the identifier of the message. The ''HelloWorldModelHelloWorld'' model has now to compute the message according to this identifier and the data stored in the database.
+
== Display the chosen message == <!--T:20-->
 +
</translate>
 +
<translate><!--T:21-->
 +
When a menu item of this component is created/updated, Joomla stores the identifier of the message. The <tt>HelloWorldModelHelloWorld</tt> model has now to compute the message according to this identifier and the data stored in the database. To do this is uses the [https://docs.joomla.org/Using_the_JTable_class JTable] functionality, which is an alternative to JDatabase if only CRUD operations on single records are required.</translate>
  
Modify the ''site/models/helloworld.php'' file:
+
<translate><!--T:22-->
 +
Modify the <tt>site/models/helloworld.php</tt> file:</translate>
  
 
<span id="site/models/helloworld.php">
 
<span id="site/models/helloworld.php">
''site/models/helloworld.php''
+
<tt>'''site/models/helloworld.php'''</tt>
 
<source lang="php">
 
<source lang="php">
 
<?php
 
<?php
Line 233: Line 304:
 
  * @subpackage  com_helloworld
 
  * @subpackage  com_helloworld
 
  *
 
  *
  * @copyright  Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
+
  * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 
  * @license    GNU General Public License version 2 or later; see LICENSE.txt
 
  * @license    GNU General Public License version 2 or later; see LICENSE.txt
 
  */
 
  */
Line 305: Line 376:
 
</span>
 
</span>
  
The model now asks the ''TableHelloWorld'' to get the message. This table class has to be defined in ''admin/tables/helloworld.php'' file
+
<translate><!--T:23-->
 +
The model now asks the ''TableHelloWorld'' to get the message. This table class has to be defined in <tt>admin/tables/helloworld.php</tt> file</translate>
  
 
<span id="admin/tables/helloworld.php">
 
<span id="admin/tables/helloworld.php">
''admin/tables/helloworld.php''
+
<tt>'''admin/tables/helloworld.php'''</tt>
 
<source lang="php">
 
<source lang="php">
 
<?php
 
<?php
Line 315: Line 387:
 
  * @subpackage  com_helloworld
 
  * @subpackage  com_helloworld
 
  *
 
  *
  * @copyright  Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
+
  * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 
  * @license    GNU General Public License version 2 or later; see LICENSE.txt
 
  * @license    GNU General Public License version 2 or later; see LICENSE.txt
 
  */
 
  */
Line 342: Line 414:
 
</span>
 
</span>
  
You shouldn't see any differences, but if you access the database you should see a table named ''jos_helloworld'' with two columns: id and greeting. And two entries: ''Hello World!'' and ''Good bye World''
+
<translate><!--T:24-->
 +
You shouldn't see any differences, but if you access the database you should see a table named ''jos_helloworld'' with two columns: id and greeting. And two entries: ''Hello World!'' and ''Good bye World''.</translate>
 +
 
 +
<translate>
 +
== Packaging the component == <!--T:25-->
 +
</translate>
  
== Packaging the component ==
+
<translate><!--T:26-->
 +
Content of your code directory</translate>
  
Content of your code directory
 
 
* ''[[#helloworld.xml|helloworld.xml]]''
 
* ''[[#helloworld.xml|helloworld.xml]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_a_view_to_the_site_part#site/helloworld.php|site/helloworld.php]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_a_view_to_the_site_part#site/helloworld.php|site/helloworld.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|site/index.html]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|site/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_a_view_to_the_site_part#site/controller.php|site/controller.php]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_a_view_to_the_site_part#site/controller.php|site/controller.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|site/views/index.html]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|site/views/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|site/views/helloworld/index.html]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|site/views/helloworld/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_a_view_to_the_site_part#site/views/helloworld/view.html.php|site/views/helloworld/view.html.php]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_a_view_to_the_site_part#site/views/helloworld/view.html.php|site/views/helloworld/view.html.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|site/views/helloworld/tmpl/index.html]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|site/views/helloworld/tmpl/index.html]]''
 
* ''[[#site/views/helloworld/tmpl/default.xml|site/views/helloworld/tmpl/default.xml]]''
 
* ''[[#site/views/helloworld/tmpl/default.xml|site/views/helloworld/tmpl/default.xml]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_a_view_to_the_site_part#site/views/helloworld/tmpl/default.php|site/views/helloworld/tmpl/default.php]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_a_view_to_the_site_part#site/views/helloworld/tmpl/default.php|site/views/helloworld/tmpl/default.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|site/models/index.html]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|site/models/index.html]]''
 
* ''[[#site/models/helloworld.php|site/models/helloworld.php]]''
 
* ''[[#site/models/helloworld.php|site/models/helloworld.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/index.html]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#admin/helloworld.php|admin/helloworld.php]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#admin/helloworld.php|admin/helloworld.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/index.html]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/index.html]]''
 
* ''[[#admin/sql/install.mysql.utf8.sql|admin/sql/install.mysql.utf8.sql]]''
 
* ''[[#admin/sql/install.mysql.utf8.sql|admin/sql/install.mysql.utf8.sql]]''
 
* ''[[#admin/sql/uninstall.mysql.utf8.sql|admin/sql/uninstall.mysql.utf8.sql]]''
 
* ''[[#admin/sql/uninstall.mysql.utf8.sql|admin/sql/uninstall.mysql.utf8.sql]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/updates/index.html]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/updates/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/updates/mysql/index.html]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/updates/mysql/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#admin/sql/updates/mysql/0.0.1.sql|admin/sql/updates/mysql/0.0.1.sql]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#admin/sql/updates/mysql/0.0.1.sql|admin/sql/updates/mysql/0.0.1.sql]]''
 
* ''[[#admin/sql/install.mysql.utf8.sql|admin/sql/updates/mysql/0.0.6.sql]]''
 
* ''[[#admin/sql/install.mysql.utf8.sql|admin/sql/updates/mysql/0.0.6.sql]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/index.html]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/fields/index.html]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/fields/index.html]]''
 
* ''[[#admin/models/fields/helloworld.php|admin/models/fields/helloworld.php]]''
 
* ''[[#admin/models/fields/helloworld.php|admin/models/fields/helloworld.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/tables/index.html]]''
+
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/tables/index.html]]''
 
* ''[[#admin/tables/helloworld.php|admin/tables/helloworld.php]]''
 
* ''[[#admin/tables/helloworld.php|admin/tables/helloworld.php]]''
  
Create a compressed file of this directory or directly download the [https://github.com/scionescire/Joomla-3.2-Hello-World-Component/archive/step-6-using-the-database.zip archive] and install it using the extension manager of Joomla. You can add a menu item of this component using the menu manager in the backend.
+
<translate><!--T:27-->
 
+
Create a compressed file of this directory or directly download the [https://github.com/scionescire/Joomla-3.2-Hello-World-Component/archive/step-6-using-the-database.zip archive] and install it using the extension manager of Joomla. You can add a menu item of this component using the menu manager in the backend.</translate>
{{notice|Please create a pull request or issue at https://github.com/joomla/Joomla-3.2-Hello-World-Component for any code discrepancies or if editing any of the source code on this page.}}
 
  
{{:J3.2:Developing a MVC Component/Navigate
+
{{notice|<translate><!--T:28-->
|prev=Adding a variable request in the menu type <!-- previous article subpage name -->
+
Please create a pull request or issue at https://github.com/joomla/Joomla-3.2-Hello-World-Component for any code discrepancies or if editing any of the source code on this page.</translate>}}
|next=Basic backend <!-- next article subpage name -->}}
 
  
== Contributors ==
+
<translate>
 +
== Contributors == <!--T:42-->
 +
</translate>
 
*[[User:cdemko|Christophe Demko]]
 
*[[User:cdemko|Christophe Demko]]
 
*[[User:oaksu|Ozgur Aksu]]
 
*[[User:oaksu|Ozgur Aksu]]
 
*[[User:scionescire|Scionescire]]
 
*[[User:scionescire|Scionescire]]
  
[[Category:Joomla! 3.0]]
+
<div class="row">
[[Category:Joomla! 3.1]]
+
<div class="large-6 columns">{{Basic button|<translate><!--T:29-->
[[Category:Joomla! 3.2]]
+
S:MyLanguage/J3.x:Developing_an_MVC_Component/Adding a variable request in the menu type|Prev: Adding a variable request in the menu type</translate>|class=expand success}}</div>
[[Category:Beginner Development]]
+
<div class="large-6 columns">{{Basic button|<translate><!--T:30-->
[[Category:Component Development]]
+
S:MyLanguage/J3.x:Developing_an_MVC_Component/Basic backend|Next: Basic backend</translate>|class=expand}}</div>
 +
</div>
 +
 
 +
<noinclude>
 +
[[Category:Joomla! 3.x{{#translation:}}]]
 +
[[Category:Joomla! 3.0{{#translation:}}]]
 +
[[Category:Joomla! 3.1{{#translation:}}]]
 +
[[Category:Joomla! 3.2{{#translation:}}]]
 +
[[Category:Joomla! 3.3{{#translation:}}]]
 +
[[Category:Joomla! 3.4{{#translation:}}]]
 +
[[Category:Beginner Development{{#translation:}}]]
 +
[[Category:Component Development{{#translation:}}]]
 +
[[Category:Tutorials{{#translation:}}]]
 +
[[Category:Tutorials in a Series{{#translation:}}]]
 +
</noinclude>

Latest revision as of 23:02, 22 January 2019

Other languages:
English • ‎Nederlands • ‎español • ‎français • ‎italiano • ‎العربية • ‎中文(台灣)‎
Joomla! 
3.x
Tutorial
Developing an MVC Component



This is a multiple-article series of tutorials on how to develop a Model-View-Controller Component for Joomla! VersionJoomla 3.x.

Begin with the Introduction, and navigate the articles in this series by using the navigation button at the bottom or the box to the right (the Articles in this series).



Introduction[edit]

This tutorial is part of the Developing an MVC Component for Joomla! 3.3 tutorial. You are encouraged to read the previous parts of the tutorial before reading this. Also while doing this part you are also encouraged to read more on database queries, selecting data from a database table and retrieving it in several formats here.

There are also 3 videos associated with this step in the tutorial, covering the Database Setup, Displaying the message (using JTable) and Admin message selection (and JDatabase).

Using the database[edit]

Components usually manage their contents using the database. During the install/uninstall/update phase of a component, you can execute SQL queries through the use of SQL text files.

With your favourite file manager and editor create two files called admin/sql/install.mysql.utf8.sql and admin/sql/updates/mysql/0.0.6.sql. They should both have the same content, as follows:

admin/sql/install.mysql.utf8.sql and admin/sql/updates/mysql/0.0.6.sql

DROP TABLE IF EXISTS `#__helloworld`;

CREATE TABLE `#__helloworld` (
	`id`       INT(11)     NOT NULL AUTO_INCREMENT,
	`greeting` VARCHAR(25) NOT NULL,
	`published` tinyint(4) NOT NULL DEFAULT '1',
	PRIMARY KEY (`id`)
)
	ENGINE =MyISAM
	AUTO_INCREMENT =0
	DEFAULT CHARSET =utf8;

INSERT INTO `#__helloworld` (`greeting`) VALUES
('Hello World!'),
('Good bye World!');

Note. Nowadays Joomla recommends specifying

ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci;

instead of what is above. InnoDB is the more modern (and now default) MySQL database engine, replacing MyISAM, and utf8mb4 supports a wider range of character sets including emojis. However, I haven't tested all the steps in the tutorial with this setting, so if you use it and go through the complete tutorial series and find no problems please consider updating this file and where it occurs in other tutorial steps.

Also note that if you look at a Joomla database many of the key database tables have a field called 'title' for the sort of information which we're storing in our 'greeting' field. It's generally advisable to follow the Joomla pattern, and use 'title' as the field name, as when we try to use more complex functionality (such as ACL and associations) some of the core Joomla javascript routines we want to reuse expect a 'title' field to be present. (Something to consider changing when this tutorial series is next updated).

Often you will find that the database table has a field to keep track of the published/unpublished state of an item. Using the name 'state' within Joomla is not recommended as it can lead to conflicts, instead the name 'published' is used.
Note: How to tell Joomla to store the value of the published form field into a different name database field? We do this by using the method setColumnAlias() (since 3.4.0).

The file install.mysql.utf8.sql will be executed when you install this component. The file 0.0.6.sql is executed when you do an update.

This is the install file. It will be executed if you put an appropriate order in the helloworld.xml file.

Important Note: When saving the SQL files in utf8, be sure to save them as utf8 NOT BOM or the query will fail with MySQL error #1064.

helloworld.xml

<?xml version="1.0" encoding="utf-8"?>
<extension type="component" version="3.0" method="upgrade">

	<name>Hello World!</name>
	<!-- The following elements are optional and free of formatting constraints -->
	<creationDate>January 2018</creationDate>
	<author>John Doe</author>
	<authorEmail>john.doe@example.org</authorEmail>
	<authorUrl>http://www.example.org</authorUrl>
	<copyright>Copyright Info</copyright>
	<license>License Info</license>
	<!--  The version string is recorded in the components table -->
	<version>0.0.6</version>
	<!-- The description is optional and defaults to the name -->
	<description>Description of the Hello World component ...</description>

	<install> <!-- Runs on install -->
		<sql>
			<file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>
		</sql>
	</install>
	<uninstall> <!-- Runs on uninstall -->
		<sql>
			<file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file>
		</sql>
	</uninstall>
	<update> <!-- Runs on update; New since J2.5 -->
		<schemas>
			<schemapath type="mysql">sql/updates/mysql</schemapath>
		</schemas>
	</update>

	<!-- Site Main File Copy Section -->
	<!-- Note the folder attribute: This attribute describes the folder
		to copy FROM in the package to install therefore files copied
		in this section are copied from /site/ in the package -->
	<files folder="site">
		<filename>index.html</filename>
		<filename>helloworld.php</filename>
		<filename>controller.php</filename>
		<folder>views</folder>
		<folder>models</folder>
	</files>

	<administration>
		<!-- Administration Menu Section -->
		<menu link='index.php?option=com_helloworld'>Hello World!</menu>
		<!-- Administration Main File Copy Section -->
		<!-- Note the folder attribute: This attribute describes the folder
			to copy FROM in the package to install therefore files copied
			in this section are copied from /admin/ in the package -->
		<files folder="admin">
			<!-- Admin Main File Copy Section -->
			<filename>index.html</filename>
			<filename>helloworld.php</filename>
			<!-- SQL files section -->
			<folder>sql</folder>
			<!-- tables files section -->
			<folder>tables</folder>
			<!-- models files section -->
			<folder>models</folder>
		</files>
	</administration>

</extension>

Do the same for the uninstall file:

With your favourite file manager and editor put a file admin/sql/uninstall.mysql.utf8.sql containing:

admin/sql/uninstall.mysql.utf8.sql

DROP TABLE IF EXISTS `#__helloworld`;

Schema Numbering[edit]

Your component has a version number (which is specified inside the <version> tag in your helloword.xml manifest file), and your component's database schema has its own version number (which is based on the filenames of the sql update files).

Joomla keeps track of the database schema version of your component through a record in its #__schemas table. So when you first install a component, if there's a file called, say, admin/sql/updates/mysql/0.0.6.sql, then Joomla will store the value 0.0.6 it its schemas record.

When you next install a newer version of this component - it doesn't have to be the next version, you can skip versions - Joomla will do the following:

  • it will retrieve the component's latest database schema version from its #__schemas table - so it might find in our example the value 0.0.6.
  • it will get the filenames of all the files in the admin/sql/updates/mysql/ directory, and organise them in numerically increasing order.
  • it will process in order the update files which have filenames numerically after the current schema version - so it might find files called 0.0.7.sql, 0.0.9.sql and 0.0.10.sql, and process these in order.
  • it will update the schemas record to have the number of the last update file which it processed - eg 0.0.10.

If you have already released versions of your component when you introduce database use, as we have simulated in this tutorial series, then your first update file must have exactly the same content as the install file. If you have not, then it should be empty.

Although it may be a good idea to keep the two version numbers in step, you don't have to. Joomla takes the schema version from the name of the numerically last update file. That's why it is recommended that there should be an initial update file, even if it's empty. If you want to keep your schema numbers in step with the component version numbers when you update your code but not the database schema, you simply include an update file to go with the new release number, and that update file, too, will be empty.

As you make subsequent releases of your component the database install file must always contain the full schema and the update files only need to contain any changes you have made to the schema since the last update.

Adding a new field type[edit]

For the moment, we have used a hard coded field type for messages. We need to use our database for choosing the message, and for this we need to define a custom field type (which we call helloworld below) as described here.

Modify the site/views/helloworld/tmpl/default.xml file and put these lines

site/views/helloworld/tmpl/default.xml

<?xml version="1.0" encoding="utf-8"?>
<metadata>
	<layout title="COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_TITLE">
		<message>COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_DESC</message>
	</layout>
	<fields
			name="request"
			addfieldpath="/administrator/components/com_helloworld/models/fields"
			>
		<fieldset name="request">
			<field
					name="id"
					type="helloworld"
					label="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL"
					description="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC"
					/>
		</fieldset>
	</fields>
</metadata>

It introduces a new field type and tells Joomla to look for the field definition in the /administrator/components/com_helloworld/models/fields folder.

In order to learn more on database queries, selecting data from a database table and retrieving it in several formats click here. With your favourite file manager and editor put a file admin/models/fields/helloworld.php containing:

admin/models/fields/helloworld.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

JFormHelper::loadFieldClass('list');

/**
 * HelloWorld Form Field class for the HelloWorld component
 *
 * @since  0.0.1
 */
class JFormFieldHelloWorld extends JFormFieldList
{
	/**
	 * The field type.
	 *
	 * @var         string
	 */
	protected $type = 'HelloWorld';

	/**
	 * Method to get a list of options for a list input.
	 *
	 * @return  array  An array of JHtml options.
	 */
	protected function getOptions()
	{
		$db    = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->select('id,greeting');
		$query->from('#__helloworld');
		$db->setQuery((string) $query);
		$messages = $db->loadObjectList();
		$options  = array();

		if ($messages)
		{
			foreach ($messages as $message)
			{
				$options[] = JHtml::_('select.option', $message->id, $message->greeting);
			}
		}

		$options = array_merge(parent::getOptions(), $options);

		return $options;
	}
}

The new field type displays a drop-down list of messages to choose from. You can see the result of this change in the menu manager section for the helloworld item.

Display the chosen message[edit]

When a menu item of this component is created/updated, Joomla stores the identifier of the message. The HelloWorldModelHelloWorld model has now to compute the message according to this identifier and the data stored in the database. To do this is uses the JTable functionality, which is an alternative to JDatabase if only CRUD operations on single records are required.

Modify the site/models/helloworld.php file:

site/models/helloworld.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

/**
 * HelloWorld Model
 *
 * @since  0.0.1
 */
class HelloWorldModelHelloWorld extends JModelItem
{
	/**
	 * @var array messages
	 */
	protected $messages;

	/**
	 * Method to get a table object, load it if necessary.
	 *
	 * @param   string  $type    The table name. Optional.
	 * @param   string  $prefix  The class prefix. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable  A JTable object
	 *
	 * @since   1.6
	 */
	public function getTable($type = 'HelloWorld', $prefix = 'HelloWorldTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Get the message
	 *
	 * @param   integer  $id  Greeting Id
	 *
	 * @return  string        Fetched String from Table for relevant Id
	 */
	public function getMsg($id = 1)
	{
		if (!is_array($this->messages))
		{
			$this->messages = array();
		}

		if (!isset($this->messages[$id]))
		{
			// Request the selected id
			$jinput = JFactory::getApplication()->input;
			$id     = $jinput->get('id', 1, 'INT');

			// Get a TableHelloWorld instance
			$table = $this->getTable();

			// Load the message
			$table->load($id);

			// Assign the message
			$this->messages[$id] = $table->greeting;
		}

		return $this->messages[$id];
	}
}

The model now asks the TableHelloWorld to get the message. This table class has to be defined in admin/tables/helloworld.php file

admin/tables/helloworld.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */
// No direct access
defined('_JEXEC') or die('Restricted access');

/**
 * Hello Table class
 *
 * @since  0.0.1
 */
class HelloWorldTableHelloWorld extends JTable
{
	/**
	 * Constructor
	 *
	 * @param   JDatabaseDriver  &$db  A database connector object
	 */
	function __construct(&$db)
	{
		parent::__construct('#__helloworld', 'id', $db);
	}
}

You shouldn't see any differences, but if you access the database you should see a table named jos_helloworld with two columns: id and greeting. And two entries: Hello World! and Good bye World.

Packaging the component[edit]

Content of your code directory

Create a compressed file of this directory or directly download the archive and install it using the extension manager of Joomla. You can add a menu item of this component using the menu manager in the backend.

Info non-talk.png
General Information

Please create a pull request or issue at https://github.com/joomla/Joomla-3.2-Hello-World-Component for any code discrepancies or if editing any of the source code on this page.

Contributors[edit]