Difference between revisions of "モジュール 開発"

From Dolibarr ERP CRM Wiki
Jump to navigation Jump to search
(初期翻訳: Enから複製)
Tag: 2017 source edit
 
m (Adding interlang links (links to translated versions of this page in other languages) triggered by origin English page "Module_development" update.)
 
(17 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<!-- BEGIN origin interlang links -->
+
<!-- BEGIN interlang links -->
<!-- You can edit this section but do NOT remove these comments
+
<!-- Do NOT edit this section
     Links below will be automatically replicated on translated pages by PolyglotBot -->
+
     Links below are automatically managed by PolyglotBot
 +
    You can edit links on the English source page : Module_development -->
 +
[[en:Module_development]]
 
[[fr:Développement_module]]
 
[[fr:Développement_module]]
 
[[es:Desarrollo_de_un_módulo]]
 
[[es:Desarrollo_de_un_módulo]]
Line 11: Line 13:
 
{{TemplateDocDevEn}}
 
{{TemplateDocDevEn}}
  
Dolibarr向け新規 モジュール/アドオン を作成するには, 複数のステップがある. このチュートリアルで説明するのは、Dolibarrの特質拡張用モジュールを作るステップのそれぞれである, 以下の1つとか、複数の組み合わせとかのように :
+
Dolibarr向け新規 モジュール/アドオン を作成するには, 複数のステップがある. このチュートリアルで記述するのは、Dolibarrの特質拡張用モジュールを作るステップのそれぞれである, 以下の1つとか、複数の組み合わせとかのように :
  
*Add new tables in database.
+
*データベースに新規テーブルを追加.
*Add your own menu entries.
+
*自前メニュー項目を追加.
*Add new screens to edit new tables.
+
*新規テーブル編集用の新規画面を追加.
*Add or remove tabs on object view (invoice, product, order, event, ...).
+
*オブジェクトビュー (請求,製品,注文,イベント, ...) に関わるタブの追加または削除.
*Add predefined exports for the internal export tool.
+
*内部エキスポートツール向けの事前定義済のエクスポートを追加.
*Add new information widget in the home page.
+
*ホームページに新規情報ウィジェットを追加.
*Add new substitutions variables.
+
*新規置換変数を追加.
*Define new permissions.
+
*新規許認可を定義.
*Execute code automatically triggered by a particular Dolibarr action.
+
*特定の Dolibarr アクションにより自動トリガされるコードを実行.
*Insert your code inside Dolibarr hooks positions.
+
*Dolibarr フックポジション内に自分のコードを挿入.
*Add your numbering rule to generate the reference of objects
+
*オブジェクト参照を生成するための自前の番号付けルールを追加
*Add a new document template.
+
*新規文書テンプレートを追加.
*Add a new skin.
+
*新規スキンを追加.
  
 
etc...
 
etc...
  
Following chapters presents how to do all of this manually with an easy way.
+
以下の章では、これらすべてを手作業で簡単に行う方法を示す.
  
=Module creation with the module builder=
+
=モジュールビルダ によるモジュールの生成=
From Dolibarr 9.0 it is possible to create the main pages of your module with the Module Builder. To activate it:
+
Dolibarr 9.0 から、モジュールビルダにより、自前モジュールのメインページ作成が可能. 起動方法は:
  
*Go into the list of module and enable the module "Module Builder",
+
*モジュールリストにて、"モジュールビルダ(Module Builder)"を有効化する,
  
 
[[File:Mod_builder_2.png|400px]]
 
[[File:Mod_builder_2.png|400px]]
  
*Then click on the "bug" image in the top right of screen.
+
*その後 "バグ(bug)" 画像をクリック、場所は画面右上.
  
 
[[File:Mod_builder_3.png|400px]]
 
[[File:Mod_builder_3.png|400px]]
  
=Example of Template External Module=
+
=テンプレート外部モジュールの例=
A good model to start development of external module can be found here : [https://github.com/Dolibarr/dolibarr/tree/develop/htdocs/modulebuilder/template GitHub Dolibarr Module Modèle]
+
外部モジュールの開発を開始するのによいお手本は、ここで見つかるだろう : [https://github.com/Dolibarr/dolibarr/tree/develop/htdocs/modulebuilder/template GitHub Dolibarr Module Modèle]
  
=Create your module=
+
=自前モジュールを作る=
==Create a Module descriptor for your Module (required)==
+
==自前モジュールに関するモジュール記述(Module descriptor)を作る (必須)==
'''When it is required''': Required as soon as an addon is developed, whatever its goal is (except for adding a skin).
+
'''必須となる時期''': アドオンを開発すると早急に必要、たとえゴールが何であれ (例外はスキンの追加).
  
'''Since Dolibarr 9.0, you should use the ModuleBuilder module provided as a standard module to generate the module descriptor'''
+
'''Dolibarr 9.0 から, モジュールビルダ (ModuleBuilder) モジュールを使用すべきだ、モジュール記述を生成するための標準モデルとして使える'''
  
===Create your module descriptor===
+
===自前のモジュール記述 (module descriptor) を作成する===
The first step is to create a file descriptor for the module.  
+
最初のステップは、モジュールに対するファイル記述 (file descriptor) を作成すること. (訳者注: 以下の内容は'''モジュールビルダを使うことで自動設定'''される)
  
*Create directory '''/htdocs/custom/''mymodule''/core/modules''' (for an external module) or '''/htdocs/''mymodule''/core/modules''' if you plan to have this module an official core module of Dolibarr. Then copy the file modMyModule.class.php from the directory '''htdocs/modulebuilder/template''' into this directory. Change the name of the file modMyModule.class.php to the name corresponding to the purpose of your module. Name of the file must start with initial 'mod' and end with .class.php (for example if you want to give the name 'NewName' to this file, then the name should be 'modNewName.class.php').
+
*ディレクトリ作成: '''/htdocs/custom/''mymodule''/core/modules''' (外部モジュール向け) または '''/htdocs/''mymodule''/core/modules''' ここはDolibarr の公式コアモジュール (official core module) とする場合. 次にファイル modMyModule.class.php をディレクトリ '''htdocs/modulebuilder/template''' からコピーして上記のディレクトリに作成. ファイルの名称を modMyModule.class.php から 自前モジュールの目的に合致した名称に変更. ファイル名は、先頭に 'mod' があり、最後が .class.php で終わる (例えば、ファイル名を '新名' にするなら, 'mod新名.class.php' となる).
  
Next modify the contents of this file as follows:
+
次は、ファイルの内容を以下のように変更:
  
*Replace all "modMyModule" with a value which corresponds to the purpose of your module. This value must always start with 'mod' and contain only alpha characters (again, if the name given to the file was 'NewName', then replace all "modMyModule" with "modNewName").
+
*すべての "modMyModule" をモジュールの目的に合致した値に置換. この値は必ず 'mod' で始まりアルファベットのみで構成 (繰り返すが, もしファイルに付けた名称が 'NewName' なら, すべての "modMyModule" "modNewName" で置換).
*Change the number in: $this->numero = 100000 by a number that designates your module id. To avoid conflicts with other modules, you can consult the page that lists already reserved id numbers: [[List of modules id|List of modules id]].
+
*番号を変更: $this->numero = 100000 の部分で、自前モジュールIDを指定する値に. 他のモジュールとの競合を避けるため、すでに予約されているid番号の一覧ページを参考にできる: [[List of modules id|List of modules id]].
*Modify any other variables defined in the constructor (see comment in the code skeleton for their meaning).
+
*コンストラクタで定義されたその他の変数(意味についてはコード雛形のコメントを参照)を変更.
  
Your file descriptor for your module is ready. See the next step to activate it.
+
自前モジュールのファイルディスクリプタの準備ができた。有効化するには次ステップを参照.
  
===Test your descriptor===
+
===自前記述をテストする===
  
Launch Dolibarr and go to page '''Setup->module'''?  
+
Dolibarrを起動し、'''設定->モジュール (Setup->module'''?) ページを表示.
If you set the property version in the module description you should see a new line with your new module and the possibility to activate it or not. If you set the property version to "develop" or "experiental", to see your module, you must first go into '''Setup-Others''' and set MAIN_FEATURES_LEVEL to 1 to see "experimental" modules or 2 to see "development" modules.
+
モジュール記述でプロパティバージョン (property version) を設定すると、自前の新規モジュールを載せた新規行とそれを有効化するかどうかの選択が表示されるはず. プロパティバージョンを "develop" または "experimental" に設定した場合、自前モジュールを見るには、まず '''設定->その他 (Setup-Others)''' に行き、 MAIN_FEATURES_LEVEL 1 に設定してから "experimental" モジュールを見るか、2にして から "development" モジュールを見るかする必要がある.
  
==Tree of path for new module files (required)==
+
==新規モジュールファイルに関するパスツリー (必須)==
This is how your files must be organized when building a new module (the zip file must also match this rule).
+
これは、新しいモジュールを構築する際に、ファイルをどう整理するかを示している (ZIPファイルもこのルールに合わせる必要あり).
Note: Only the second line is mandatory.
+
注:2行目だけが必須.
  
{{TemplateModuleTreeSimple}}
+
{{TemplateModuleTreeSimpleJA}}
  
==Create your SQL tables and the PHP DAO class (optional)==
+
==自前 SQL テーブル と PHP DAO クラス (任意)==
'''When''': If your module needs to manage data of its own
+
'''使用場面''': 自前モジュールがそれ自身のデータを管理する必要がある場合
  
===Create your .sql file===
+
===自前の .sql ファイルを作成===
If your module is designed to manage data of its own, which are not available in the standard version of Dolibarr, it is necessary to define SQL tables to store the data.
+
自前モジュールが、Dolibarr標準版では利用できない独自データを管理する設計である場合、そのデータを格納するためのSQLテーブルを定義する必要がある.
  
Scripts for creating tables and loading data by your own module are saved into a subdirectory sql ('''"mymodule/sql"''') of your module. (With ModuleBuilder, the directory and all sql files will be created automatically when you will create a new Object from tab Object).
+
自前モジュールでテーブルを作成したり、データを読込むためのスクリプトは、自前モジュールのsqlサブディレクトリ ("'''mymodule/sql'''") に保存される。(ModuleBuilder では、オブジェクト タブから新しいオブジェクトを作成するとき、このディレクトリとすべての sql ファイルが自動作成される).
  
Then check into your descriptor file, into function '''init''' that the line
+
次に、記述ファイルでの、'''init''' 関数にて、次の行
  
 
<syntaxhighlight lang="php">$this->_load_tables('/mymodule/sql/');</syntaxhighlight>
 
<syntaxhighlight lang="php">$this->_load_tables('/mymodule/sql/');</syntaxhighlight>
  
is not commented.
+
が、コメントでないことを確認する.
  
''Rules to follow:''
+
''従うべきルール:''
  
*Add the files about creating tables commands on the principle of a file '''llx_matable.sql''' per table, with a possibly file '''llx_matable.key.sql''' (see existing files in '''install/mysql/tables''' for examples).
+
*テーブルごとに '''llx_matable.sql''' ファイルを1つ、'''llx_matable.key.sql''' ファイルを可能なら1つ、作成するという原則に基づき、テーブル作成コマンドのファイルを追加する(例として、 '''install/mysql/tables''' にあるファイルを参照).
*The recommended type and name for SQL fields are defined into page [[Language_and_development_rules#Table_and_fields_structures]].
+
*SQLフィールドの推奨される型と名前は、このページに定義されてる [[Language_and_development_rules#Table_and_fields_structures]].
*To manage data, you must create a file called '''data.sql''' inside directory '''/mymodule/sql/''' that contains SQL command to add/edit/delete data.
+
*データ管理のため、 '''/mymodule/sql/''' ディレクトリ内に  '''data.sql''' というファイルを作成し、データの追加/編集/削除を行う SQL コマンドを記述すること.
*Don't use the double quote for strings (eg 'chaine' not "chaine") because the double quote have a specific meaning in PostGreSQL
+
*文字列にダブルクォートを使わない(例: "chaine" でなく 'chaine') ダブルクォートは PostGreSQL では特定の意味を持つ
  
Example of content of a file data.sql
+
例としてファイル data.sql の中身は
 
<syntaxhighlight lang="sql">
 
<syntaxhighlight lang="sql">
 
  delete from llx_const where name='MYMODULE_IT_WORKS' and entity='__ENTITY__';
 
  delete from llx_const where name='MYMODULE_IT_WORKS' and entity='__ENTITY__';
Line 102: Line 104:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Files must be operational for the database mysql. Rem: The files of other databases are not maintained. They will be read and converted on the fly by the driver of the other database.
+
ファイルは、mysql データベースで動作可能であること. 備考: 他データベースのファイルはメンテナンスされない. 他データベースのドライバによって、その場で読込まれ変換さる.
  
===Test your .sql files===
+
===自前の  .sql ファイルをテストする===
  
Once the files ready, you can return to the page to enable Dolibarr modules and disable the module, drop those tables in the database (if they already exists) and reactivate the module. The tables should be recreated by the activation of the module. If this is not the case, check your scripts by passing them by hand, or check the Dolibarr logs.
+
ファイルの準備ができたら、Dolibarrモジュールを有効にするページに戻り、モジュールを無効にして、データベース内のそれらのテーブルを削除し(すでに存在している場合)、モジュールを再有効化することができる。モジュールの有効化により、テーブルが再作成されるはず。もしそうでない場合、スクリプトを手で渡して確認するか、Dolibarrのログを確認すること.
  
===Generate the PHP DAO class===
+
===PHP DAO クラスを生成===
The DAO PHP files should have been generated by ModuleBuilder after creating an object.
+
DAO PHPファイルは、オブジェクトを作成した後にモジュールビルダによって生成されているはず.
  
You can however create them manually by copying existing object however using ModuleBuilder is highly recommended. You should find examples into '''htdocs/modulebuilder/templates/class/myobject.class.php'''
+
だとしても、既存オブジェクトをコピーして手動作成することもできる、しかし、モジュールビルダの使用を強く勧める。実例がここにあるはず '''htdocs/modulebuilder/templates/class/myobject.class.php'''
  
In this class, there are already operational CRUD (Create/Read/Update/Delete) methods to perform an insert, a fetch (select), an update, a delete of a table row. Edit the file to use the correct module name, tables and place this file in the class subdirectory of the module. The Module Builder allows you to do this with just a few mouse clicks.
+
このクラスでは、テーブル行の挿入、取得(選択)、更新、削除を実行するためのCRUD(作成/読込/更新/削除)メソッドがすでに実行可能となっている。正しいモジュール名、テーブルを使用するようにファイルを編集し、このファイルをモジュールのクラスサブディレクトリに配置する。モジュールビルダを使用すると、マウスを数回クリックするだけで、この作業を実行できる.
  
==The tab management (optional)==
+
==タブ管理 (任意)==
  
===Add or remove your own tabs on object sheets===
+
===オブジェクトシートに自前のタブを追加・削除できる===
'''When''': To add a tab on an object (invoices, orders, proposals, member ...)
+
'''使用場面''': オブジェクト(請求書、注文書、提案書、メンバー...)にタブを追加する場合
  
To do this go into the file descriptor of module previously created and edit the $this->tabs array:
+
そのためには、先に作成したモジュールのファイル記述に行って、$this->tabs 配列を編集する:
  
 
<syntaxhighlight lang="php">
 
<syntaxhighlight lang="php">
Line 129: Line 131:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
The table should contain a list of strings, each string representing a new tab.
+
テーブルには文字列のリストが含まれ、各文字列は新しいタブを表す.文字列の形式は ": " で区切られた5つの部分からなる.
The format of the string consisting of 5 parts separated by ":"
 
  
*Part 1: The element type (object type) where the tab should appear is a value from the following:
+
*Part 1: タブを表示するエレメントタイプ(オブジェクトタイプ)で、以下の値:
{{TemplateModuleTabs}}
+
{{TemplateModuleTabsJA}}
  
*Part 2: A code to identify tab to add (start with +) or to remove (start with -)
+
*Part 2: タブのコードで、タブの追加(+で始まる)または削除(-で始まる)を識別する.
*Part 3: The title of the tab. This can be a hard read or better code translation in a file lang.
+
*Part 3: タブのタイトル.タイトルが読みずらいなら、コードにして言語ファイルで翻訳するとよい.
*Part 4: The name of the file "*.lang" which contains correspondence between the code translation and language to display. If this name is followed with @mymodule, Dolibarr will search translation file "*.lang" within the module, so htdocs/mymodule/langs/code_CODE/mylangfile.lang, otherwise Dolibarr will look for file htdocs/langs/code_CODE/mylangfile.lang
+
*Part 4: ファイル名 "*.lang" は、コード翻訳と表示する言語の対応を含む.この名前の後に@mymoduleが続く場合、 Dolibarrはモジュール内の翻訳ファイル "*.lang "を検索するので、htdocs/mymodule/langs/code_CODE/mylangfile.langとなり、そうでない場合はhtdocs/langs/code_CODE/mylangfile.langとなる.
*Part 5: A condition to test if tab must be visible. Put 1 to be always visible.
+
*Part 5: タブを常時表示すべきかのテスト条件.常時表示の場合は1を指定.
*Part 6: The URL of the page to display when you click on the tab. The __ID__ string will be replaced automatically by the Id of the element concerned.
+
*Part 6: タブをクリックしたときに表示されるページのURL。__ID__の文字列は自動的に当該要素のIdに置き換えられる.
  
To feed the contents of the tab with data from the database, see the next chapter.
+
タブの内容へデータベースからのデータを注入するには、次章を参照.
  
In order to get the names  'tabname' of existing tabs, you have to check the names used in the function 'product_prepare_head' of the file  'core/lib/module.lib.php' corresponding to section '$head[$h][2]'.
+
既存タブの名前 'tabname' を取得するには、ファイル 'core/lib/module.lib.php' の関数 'product_prepare_head' で使用されている名前で、セクション '$head[$h][2]' に対応するものをチェックする必要がある.
  
===Show tabs navigation into your own pages===
+
===自前ページにタブナビゲーションを表示===
'''When''': To show all standard tabs of an object (product, tiers, etc.) on your page.
+
'''使用場面''': 自前ページにオブジェクト(製品、階層、など)の標準タブを表示したい
  
You must follow these steps :
+
以下の手順に従う :
  
 
'''1. Include files you need into your file'''
 
'''1. Include files you need into your file'''
Line 217: Line 218:
 
This function will show required tabs and open an html element ''< div class="" >'' that correspond to the area under the tabs. To close area of a tab, just use ''< /div >'' into your PHP page.
 
This function will show required tabs and open an html element ''< div class="" >'' that correspond to the area under the tabs. To close area of a tab, just use ''< /div >'' into your PHP page.
  
==Create or modify PHP screens (optional)==
+
==PHP 画面の作成や更新 (任意)==
'''When''': If the purpose of your module is to add features that require new or modified screens.
+
使用場面: モジュールの目的が、画面の新規作成または変更を必要とする機能の追加である場合.
  
===Create a new PHP screen===
+
===新規 PHP 画面の作成===
You must then create your PHP pages that will show/edit data from tables using the skeleton templates provided as an example in the directory '''modulebuilder/myobject_page.php''' (For the development of a script from the command line, see [[Script development]]).
+
次に、 '''modulebuilder/myobject_page.php''' ディレクトリに例として提示されているスケルトンテンプレートを使用して、テーブルのデータを表示/編集するPHPページを作成する必要がある (コマンドラインからのスクリプト開発については、 [[Script development]] を参照).
  
To create a new user screen, create a subdirectory of '''htdocs''' (if not already done) for your module (in '''htdocs/mymodule''' for example) to store the pages you will create.
+
新しいユーザー画面を作成するには、'''htdocs''' のサブディレクトリを作成し(まだ作成されていない場合)、作成するページを保存するために、モジュール(例えば、'''htdocs/mymodule''' )のサブディレクトリを作成する.
  
Copy, into that directory, the file '''myobject_page.phpp''' that will serve as a starting point for your page file.
+
そのディレクトリに、ページファイルの出発点となるファイル '''myobject_page.php''' をコピーする。.
Edit the file to have a correct relative path to the main.inc.php file.  
+
main.inc.phpファイルへの相対パスが正しくなるようにファイルを編集する.  
 
<syntaxhighlight lang="php">
 
<syntaxhighlight lang="php">
 
// Load Dolibarr environment
 
// Load Dolibarr environment
Line 243: Line 244:
 
if (! $res) die("Include of main fails");
 
if (! $res) die("Include of main fails");
 
</syntaxhighlight>
 
</syntaxhighlight>
As you can see, there are several tries to load the main.inc.php (or master.inc.php). The goal is to succeed in the most cases as possible. The minimum is 2 lines: one to try to load the master/main.inc.php into the dolibarr root directory and another one to try to load the file to support the case when the module is deployed into the "custom" directory. But you can have more to deal more situation. The provided example should be able to load the file main/master.inc.php in nearly all situation/setups.
+
ご覧のように、main.inc.php(または master.inc.php)のロードは何回か試行される。目標は、大抵のケースで成功すること。最小は2行: master/main.inc.phpをdolibarrルートディレクトリにロードしようとする行と、モジュールが "custom "ディレクトリにデプロイされるケースをサポートするためにファイルをロードしようとする行。しかし、より多くの状況に対応するため、より多くを持つことができる。提供された例は、ほぼすべての状況/セットアップで main/master.inc.php ファイルをロードできるはず。
  
Note that you may add more "../" depending on the depth of the file relative to your module directory tree.
+
注意: モジュール・ディレクトリ・ツリーに対するファイルの深さによっては、さらに"../"を追加する。
  
It's in the main.inc.php file that is loaded technical environment variables and permissions. The following variables are objects positioned in this file:
+
main.inc.phpファイルでは、技術上の環境変数とパーミッションを読み込む。以下の変数はこのファイルに配置されているオブジェクト:
  
*$user    Object that contains the characteristics of the user + his permissions.
+
*$user    ユーザーの特徴とパーミッションを保持するオブジェクト。
*$conf    Object that contains Dolibarr configuration.
+
*$conf    Dolibarrの設定を保持するオブジェクト
*$db      Object that contains an opened connection handler to the database.
+
*$db      データベースへのオープンされた接続ハンドラを保持するオブジェクト。
*$langs  Object that contains the user's language.
+
*$langs  ユーザー言語を保持するオブジェクト。
  
Then enter your code to display the page.
+
次にページを表示するために自前コードを入力する.
  
*To include a class or library dedicated to the module is done using a Dolibarr function (and not using directly include_once):
+
*モジュール専用クラスやライブラリをインクルードするには、(include_onceを直接使わず)Dolibarr関数を使う:
  
 
''Example :''
 
''Example :''
Line 263: Line 264:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
*To include classes provided with Dolibarr, use the following syntax:
+
*Dolibarrで提供されているクラスをインクルードするには、以下の構文を使う:
  
 
''Example :''
 
''Example :''
Line 286: Line 287:
 
See chapter [[Hooks_system#Implement_the_Hook]] to know how to use Dolibarr existing hooks to add/replace code at Dolibarr hooks place.
 
See chapter [[Hooks_system#Implement_the_Hook]] to know how to use Dolibarr existing hooks to add/replace code at Dolibarr hooks place.
  
===Database access===
+
===データベース アクセス===
If you need to edit some data in the database inside your own table, use the PHP class generated before.
+
自前テーブルの中でデータベースのデータを編集する必要がある場合、前に生成されたPHPクラスを使うこと。
  
If you to make access to tables with no dedicated PHP class available, this is always possible (for example if you want to get a list of records with a particular join or filter). In this case, this is a code samples to follow:
+
専用の PHP クラスがないテーブルにアクセスしたい場合 (たとえば、特定の結合やフィルタを使用したレコードの一覧を取得したい場合など) 、これはいつでも可能。この場合に、倣うべきコード例は:
  
To make an insert, update or delete:
+
操作が、 insert, update または delete:
  
 
<syntaxhighlight lang="php">
 
<syntaxhighlight lang="php">
Line 300: Line 301:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
To read:
+
操作が read:
  
 
<syntaxhighlight lang="php">
 
<syntaxhighlight lang="php">
Line 359: Line 360:
 
as soon as the module is activate, the tpl will be overwrited
 
as soon as the module is activate, the tpl will be overwrited
  
==Add your own setup page (optional)==
+
==自前の準備ページを追加 (任意)==
 
'''When''': If your module needs parameters, which are to be provided by the user, for proper setting up of the module.
 
'''When''': If your module needs parameters, which are to be provided by the user, for proper setting up of the module.
  
Line 382: Line 383:
 
Go into page '''Home->Setup->Modules''', you should see a picture at the end of the line of your module to reach your setup page. Click on it, you should be able to view/edit parameters from your page.
 
Go into page '''Home->Setup->Modules''', you should see a picture at the end of the line of your module to reach your setup page. Click on it, you should be able to view/edit parameters from your page.
  
==Define your entries in menu (optional)==
+
==メニューに自前項目を定義 (任意)==
 
'''When''': If you have created PHP pages, it is necessary that those pages can be reached from menu entries in Dolibarr menu.
 
'''When''': If you have created PHP pages, it is necessary that those pages can be reached from menu entries in Dolibarr menu.
  
Line 433: Line 434:
 
Disable and re-enable your module under the Dolibarr module setup page, menus entries must appear (if property 'enabled' is declaration array is ok).
 
Disable and re-enable your module under the Dolibarr module setup page, menus entries must appear (if property 'enabled' is declaration array is ok).
  
==Add your own permissions (optional)==
+
==自前の許認可を追加 (任意)==
 
'''When''': If you want to add new permissions.
 
'''When''': If you want to add new permissions.
  
Line 465: Line 466:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==Define your own box (optional)==
+
==自前の box を定義 (任意)==
 
'''When''': If your module needs to provide one or several new boxes to show on home page.
 
'''When''': If your module needs to provide one or several new boxes to show on home page.
  
Line 490: Line 491:
 
Your boxes must appear in the list of boxes you can activate. Activate the box and go on the home page to see if the box is showing correctly.
 
Your boxes must appear in the list of boxes you can activate. Activate the box and go on the home page to see if the box is showing correctly.
  
==Define your own export (optional)==
+
==自前のエキスポートを定義 (任意)==
 
'''When''': If your module provides new predefined database export profiles (for its own tables or for already existing tables of another module).
 
'''When''': If your module provides new predefined database export profiles (for its own tables or for already existing tables of another module).
  
Line 501: Line 502:
 
Choose on field and try to build an export file. If ok, try again with all fields.
 
Choose on field and try to build an export file. If ok, try again with all fields.
  
==Define your CSS styles (optional)==
+
==自前の CSS スタイルを定義 (任意)==
 
'''When''': If in your PHP pages, you use class styles that are not defined inside Dolibarr themes CSS (not recommanded).
 
'''When''': If in your PHP pages, you use class styles that are not defined inside Dolibarr themes CSS (not recommanded).
  
Line 522: Line 523:
 
You should see into the HTML header, a line that declares your style sheet.
 
You should see into the HTML header, a line that declares your style sheet.
  
==Add your Javascript functions (optional)==
+
==自前の Javascript 関数を追加 (任意)==
 
'''When''': If in your PHP pages, you use javascript functions not available in Dolibarr (in file lib_head.js)
 
'''When''': If in your PHP pages, you use javascript functions not available in Dolibarr (in file lib_head.js)
  
Line 534: Line 535:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==Run your own code on any Dolibarr event (optional)==
+
==いずれかの Dolibarr イベントで自前コードを実行する (任意)==
 
'''When''': If you want to execute your own code once a common Dolibarr event has occurred (example: I want to update a table in my module when an invoice is created into Dolibarr), you must create a '''triggers'''.
 
'''When''': If you want to execute your own code once a common Dolibarr event has occurred (example: I want to update a table in my module when an invoice is created into Dolibarr), you must create a '''triggers'''.
  
Line 540: Line 541:
 
and [[Interfaces_from_foreign_systems_toward_Dolibarr]]
 
and [[Interfaces_from_foreign_systems_toward_Dolibarr]]
  
==Insert your code inside Dolibarr hooks positions (optional)==
+
==Dolibarr フックポジションの内部に、自前コードを挿入 (任意)==
 
'''When''': When you want to add code or replace Dolibarr code into another situation than a business event (See the previous chapter for adding code during a business event).
 
'''When''': When you want to add code or replace Dolibarr code into another situation than a business event (See the previous chapter for adding code during a business event).
  
Line 546: Line 547:
  
  
==Add your own numbering rules==
+
==自前の番号付けルールを追加==
 
'''When''': When you need a new rule for generated ref of elements that are not covered by existing rules.
 
'''When''': When you need a new rule for generated ref of elements that are not covered by existing rules.
  
 
See page [[Create numbering module]].
 
See page [[Create numbering module]].
  
==Add your document template (optional)==
+
==自前の文書テンプレートを追加 (任意)==
 
'''When''': When you want to personalized your own generated PDF or ODT documents.
 
'''When''': When you want to personalized your own generated PDF or ODT documents.
  
Line 558: Line 559:
 
Documentation to add your own template is available on page [[Create_a_PDF_document_template]] or [[Create_an_ODT_document_template]].
 
Documentation to add your own template is available on page [[Create_a_PDF_document_template]] or [[Create_an_ODT_document_template]].
  
==Add your skin (optional)==
+
==自前のスキンを追加 (任意)==
 
'''When''': When you want to personalized your colors/fonts/images.
 
'''When''': When you want to personalized your colors/fonts/images.
  
Line 565: Line 566:
 
To add your own skin, read page [[Skins]].
 
To add your own skin, read page [[Skins]].
  
=Some coding rules and predefined functions=
+
=コーディングルールおよび定義済み関数=
 
The coding rules to be followed are defined in the [[Developer documentation]], under section "General Information - Language and standards development".
 
The coding rules to be followed are defined in the [[Developer documentation]], under section "General Information - Language and standards development".
  
 
A lot of predefined features for developers are also available and described into page [[Developer documentation]] under section "Technical components of Dolibarr".
 
A lot of predefined features for developers are also available and described into page [[Developer documentation]] under section "Technical components of Dolibarr".
  
=Create a package to distribute and install your module=
+
=自前モジュールを配布し導入するためのパッケージを作成=
 
This process must be used to generate a package to submit it on the http://www.dolistore.com marketplace.
 
This process must be used to generate a package to submit it on the http://www.dolistore.com marketplace.
 
But you can use it to have a package easy to distribute on your own network.
 
But you can use it to have a package easy to distribute on your own network.
Line 595: Line 596:
 
**If quality is enough and license permits it, the code might be added inside main Dolibarr sources (except if you disagree for that).
 
**If quality is enough and license permits it, the code might be added inside main Dolibarr sources (except if you disagree for that).
  
=Enabling/activation condition of external module on DoliStore=
+
=DoliStore での外部モジュール 有効化/活性化 条件=
  
 
See [[Module_Dolistore_Validation_Rules|Validation Rules]]
 
See [[Module_Dolistore_Validation_Rules|Validation Rules]]
 
[[Category:Development]]
 
[[Category:Development]]

Latest revision as of 07:58, 18 September 2023

Dolibarr向け新規 モジュール/アドオン を作成するには, 複数のステップがある. このチュートリアルで記述するのは、Dolibarrの特質拡張用モジュールを作るステップのそれぞれである, 以下の1つとか、複数の組み合わせとかのように :

  • データベースに新規テーブルを追加.
  • 自前メニュー項目を追加.
  • 新規テーブル編集用の新規画面を追加.
  • オブジェクトビュー (請求,製品,注文,イベント, ...) に関わるタブの追加または削除.
  • 内部エキスポートツール向けの事前定義済のエクスポートを追加.
  • ホームページに新規情報ウィジェットを追加.
  • 新規置換変数を追加.
  • 新規許認可を定義.
  • 特定の Dolibarr アクションにより自動トリガされるコードを実行.
  • Dolibarr フックポジション内に自分のコードを挿入.
  • オブジェクト参照を生成するための自前の番号付けルールを追加
  • 新規文書テンプレートを追加.
  • 新規スキンを追加.

etc...

以下の章では、これらすべてを手作業で簡単に行う方法を示す.

モジュールビルダ によるモジュールの生成

Dolibarr 9.0 から、モジュールビルダにより、自前モジュールのメインページ作成が可能. 起動方法は:

  • モジュールリストにて、"モジュールビルダ(Module Builder)"を有効化する,

Mod builder 2.png

  • その後 "バグ(bug)" 画像をクリック、場所は画面右上.

Mod builder 3.png

テンプレート外部モジュールの例

外部モジュールの開発を開始するのによいお手本は、ここで見つかるだろう : GitHub Dolibarr Module Modèle

自前モジュールを作る

自前モジュールに関するモジュール記述(Module descriptor)を作る (必須)

必須となる時期: アドオンを開発すると早急に必要、たとえゴールが何であれ (例外はスキンの追加).

Dolibarr 9.0 から, モジュールビルダ (ModuleBuilder) モジュールを使用すべきだ、モジュール記述を生成するための標準モデルとして使える

自前のモジュール記述 (module descriptor) を作成する

最初のステップは、モジュールに対するファイル記述 (file descriptor) を作成すること. (訳者注: 以下の内容はモジュールビルダを使うことで自動設定される)

  • ディレクトリ作成: /htdocs/custom/mymodule/core/modules (外部モジュール向け) または /htdocs/mymodule/core/modules ここはDolibarr の公式コアモジュール (official core module) とする場合. 次にファイル modMyModule.class.php をディレクトリ htdocs/modulebuilder/template からコピーして上記のディレクトリに作成. ファイルの名称を modMyModule.class.php から 自前モジュールの目的に合致した名称に変更. ファイル名は、先頭に 'mod' があり、最後が .class.php で終わる (例えば、ファイル名を '新名' にするなら, 'mod新名.class.php' となる).

次は、ファイルの内容を以下のように変更:

  • すべての "modMyModule" をモジュールの目的に合致した値に置換. この値は必ず 'mod' で始まりアルファベットのみで構成 (繰り返すが, もしファイルに付けた名称が 'NewName' なら, すべての "modMyModule" を "modNewName" で置換).
  • 番号を変更: $this->numero = 100000 の部分で、自前モジュールIDを指定する値に. 他のモジュールとの競合を避けるため、すでに予約されているid番号の一覧ページを参考にできる: List of modules id.
  • コンストラクタで定義されたその他の変数(意味についてはコード雛形のコメントを参照)を変更.

自前モジュールのファイルディスクリプタの準備ができた。有効化するには次ステップを参照.

自前記述をテストする

Dolibarrを起動し、設定->モジュール (Setup->module?) ページを表示. モジュール記述でプロパティバージョン (property version) を設定すると、自前の新規モジュールを載せた新規行とそれを有効化するかどうかの選択が表示されるはず. プロパティバージョンを "develop" または "experimental" に設定した場合、自前モジュールを見るには、まず 設定->その他 (Setup-Others) に行き、 MAIN_FEATURES_LEVEL を 1 に設定してから "experimental" モジュールを見るか、2にして から "development" モジュールを見るかする必要がある.

新規モジュールファイルに関するパスツリー (必須)

これは、新しいモジュールを構築する際に、ファイルをどう整理するかを示している (ZIPファイルもこのルールに合わせる必要あり). 注:2行目だけが必須.

  • mymodule/* には php ページを配置(任意のサブディレクトリ追加も可であることに注意)注: 自前モジュールがメタパッケージ(同一 zip 内に他モジュールを埋め込むモジュールである場合、ここに metapackage.conf ファイルを置く必要がある)
  • mymodule/build/ には任意のファイルを配置でき、それはコンパイルやビルドに使用するもの
  • mymodule/core/modules/ には、モジュール記述ファイル modMyModule.class.php を配置
  • mymodule/core/triggers には、モジュールが提供するトリガーを配置
  • mymodule/admin/ には、モジュールを設定するページを配置
  • mymodule/class/ には、モジュールが提供するPHP クラスファイルを配置
  • mymodule/css には、モジュールが提供する CSS ファイルを配置
  • mymodule/js には、モジュールが提供する javascirpt ファイルを配置し、新規 function を追加
  • mymodule/docs には、文書及びライセンスファイルを配置
  • mymodule/img には、モジュールが提供する画像ファイルを配置
  • mymodule/langs/xx_XX には、言語 xx_XX (少なくと en_US は配置)に対応する言語ファイルを配置
  • mymodule/lib には、モジュールが提供し使用するライブラリを配置
  • mymodule/scripts には、コマンドラインツールやスクリプトを配置. 注: コマンドラインスクリプトの先頭行に次のもの使う #!/usr/bin/env php
  • mymodule/sql には、モジュールが提供する SQL ファイルを配置し、新規テーブルやインデックスを追加
  • mymodule/theme/mytheme モジュールが自前のテーマ/スキンを提供する場合

自前 SQL テーブル と PHP DAO クラス (任意)

使用場面: 自前モジュールがそれ自身のデータを管理する必要がある場合

自前の .sql ファイルを作成

自前モジュールが、Dolibarr標準版では利用できない独自データを管理する設計である場合、そのデータを格納するためのSQLテーブルを定義する必要がある.

自前モジュールでテーブルを作成したり、データを読込むためのスクリプトは、自前モジュールのsqlサブディレクトリ ("mymodule/sql") に保存される。(ModuleBuilder では、オブジェクト タブから新しいオブジェクトを作成するとき、このディレクトリとすべての sql ファイルが自動作成される).

次に、記述ファイルでの、init 関数にて、次の行

$this->_load_tables('/mymodule/sql/');

が、コメントでないことを確認する.

従うべきルール:

  • テーブルごとに llx_matable.sql ファイルを1つ、llx_matable.key.sql ファイルを可能なら1つ、作成するという原則に基づき、テーブル作成コマンドのファイルを追加する(例として、 install/mysql/tables にあるファイルを参照).
  • SQLフィールドの推奨される型と名前は、このページに定義されてる Language_and_development_rules#Table_and_fields_structures.
  • データ管理のため、 /mymodule/sql/ ディレクトリ内に data.sql というファイルを作成し、データの追加/編集/削除を行う SQL コマンドを記述すること.
  • 文字列にダブルクォートを使わない(例: "chaine" でなく 'chaine') ダブルクォートは PostGreSQL では特定の意味を持つ

例としてファイル data.sql の中身は

 delete from llx_const where name='MYMODULE_IT_WORKS' and entity='__ENTITY__';
 insert into llx_const (name, value, type, note, visible, entity) values ('MYMODULE_IT_WORKS','1','chaine','A constant vor my module',1,'__ENTITY__');

ファイルは、mysql データベースで動作可能であること. 備考: 他データベースのファイルはメンテナンスされない. 他データベースのドライバによって、その場で読込まれ変換さる.

自前の .sql ファイルをテストする

ファイルの準備ができたら、Dolibarrモジュールを有効にするページに戻り、モジュールを無効にして、データベース内のそれらのテーブルを削除し(すでに存在している場合)、モジュールを再有効化することができる。モジュールの有効化により、テーブルが再作成されるはず。もしそうでない場合、スクリプトを手で渡して確認するか、Dolibarrのログを確認すること.

PHP DAO クラスを生成

DAO PHPファイルは、オブジェクトを作成した後にモジュールビルダによって生成されているはず.

だとしても、既存オブジェクトをコピーして手動作成することもできる、しかし、モジュールビルダの使用を強く勧める。実例がここにあるはず htdocs/modulebuilder/templates/class/myobject.class.php

このクラスでは、テーブル行の挿入、取得(選択)、更新、削除を実行するためのCRUD(作成/読込/更新/削除)メソッドがすでに実行可能となっている。正しいモジュール名、テーブルを使用するようにファイルを編集し、このファイルをモジュールのクラスサブディレクトリに配置する。モジュールビルダを使用すると、マウスを数回クリックするだけで、この作業を実行できる.

タブ管理 (任意)

オブジェクトシートに自前のタブを追加・削除できる

使用場面: オブジェクト(請求書、注文書、提案書、メンバー...)にタブを追加する場合

そのためには、先に作成したモジュールのファイル記述に行って、$this->tabs 配列を編集する:

	// Array to add new pages in new tabs or remove existing one
	$this->tabs = array('objecttype:+tabname1:Title1:mylangfile@mymodule:$user->rights->mymodule->read:/mymodule/mypagetab1.php?id=__ID__'    // To add a new tab identified by code tabname1
                            'objecttype:+tabname2:Title2:mylangfile@mymodule:$user->rights->mymodule->read:/mymodule/mypagetab2.php?id=__ID__',   // To add a new tab identified by code tabname2
                            'objecttype:-tabname');                                                     // To remove an existing tab identified by code tabname

テーブルには文字列のリストが含まれ、各文字列は新しいタブを表す.文字列の形式は ": " で区切られた5つの部分からなる.

  • Part 1: タブを表示するエレメントタイプ(オブジェクトタイプ)で、以下の値:
    • 'thirdparty' 取引先ビューでタブ追加
    • 'intervention' 出張ビューでタブ追加
    • 'supplier_order' 仕入注文ビューでタブ追加
    • 'supplier_invoice' 仕入請求ビューでタブ追加
    • 'invoice' 顧客請求ビューでタブ追加
    • 'order' 顧客注文ビューでタブ追加
    • 'product' 製品ビューでタブ追加
    • 'stock' 在庫ビューでタブ追加
    • 'propal' 提案ビューでタブ追加
    • 'member' 財団メンバービューでタブ追加
    • 'contract' 契約ビューでタブ追加
    • 'user' ユーザビューでタブ追加
    • 'group' グループビューでタブ追加
    • 'contact' 連絡先ビューでタブ追加
    • 'payment' 支払ビューでタブ追加 (since 3.6.0)
    • 'payment_supplier' 仕入支払ビューでタブ追加 (since 3.6.0)
    • 'categories_x' 種別ビューでタブ追加 ('x' を種別タイプ (0=product, 1=supplier, 2=customer, 3=member) に変更)
  • Part 2: タブのコードで、タブの追加(+で始まる)または削除(-で始まる)を識別する.
  • Part 3: タブのタイトル.タイトルが読みずらいなら、コードにして言語ファイルで翻訳するとよい.
  • Part 4: ファイル名 "*.lang" は、コード翻訳と表示する言語の対応を含む.この名前の後に@mymoduleが続く場合、 Dolibarrはモジュール内の翻訳ファイル "*.lang "を検索するので、htdocs/mymodule/langs/code_CODE/mylangfile.langとなり、そうでない場合はhtdocs/langs/code_CODE/mylangfile.langとなる.
  • Part 5: タブを常時表示すべきかのテスト条件.常時表示の場合は1を指定.
  • Part 6: タブをクリックしたときに表示されるページのURL。__ID__の文字列は自動的に当該要素のIdに置き換えられる.

タブの内容へデータベースからのデータを注入するには、次章を参照.

既存タブの名前 'tabname' を取得するには、ファイル 'core/lib/module.lib.php' の関数 'product_prepare_head' で使用されている名前で、セクション '$head[$h][2]' に対応するものをチェックする必要がある.

自前ページにタブナビゲーションを表示

使用場面: 自前ページにオブジェクト(製品、階層、など)の標準タブを表示したい

以下の手順に従う :

1. Include files you need into your file

For each object type, there are two files to include with line

require_once($url_fichier) ;

This is example of files to include (DOL_DOCUMENT_ROOT is often dolibarr/htdocs/) :

  • Object thirdparty (thirdparty) :
    • DOL_DOCUMENT_ROOT/societe/class/societe.class.php
    • DOL_DOCUMENT_ROOT/core/lib/company.lib.php
  • Object product (product) :
    • DOL_DOCUMENT_ROOT/product/class/product.class.php
    • DOL_DOCUMENT_ROOT/core/lib/product.lib.php
  • Object invoice (invoice) :
    • DOL_DOCUMENT_ROOT/compta/facture/class/facture.class.php
    • DOL_DOCUMENT_ROOT/core/lib/invoice.lib.php

...

2. Create and load the object to show into your tab

Create an instance of an object of the correct class and load object from the database by using the fetch method of an object in providing to this method the id you get from URL (ie : /mytab.php?id=1).

Example :

$id=GETPOST('id','int');
$ref=GETPOST('ref','alpha');
$product = new Product($db) ;
$result = $product->fetch($id,$ref) ; // Test $result to check the database read is ok

3. Get a list of all tabs to show for your object type

Use function XXX_prepare_head($obj), where XXX is name of object. This will return an array with all definition of tab entries to show. The parameter to put into this method is the instance of an object you want tabs.

The resulting array has the following structure

$head        // Array of tabs
$head[$h]    // Element to describe one tab.
$head[$h][0] // Url of page to show when you click on tab
$head[$h][1] // Title of tab
$head[$h][2] // Code name to identify the tab

Example :

$head = product_prepare_head($product, $user) ; // parameter $user is present for some function anly

4. show tabs into your page

Use function dol_fiche_head() to show all tabs defined into array $head returned by XX_prepare_head().

dol_fiche_head($links, $active='0', $title='', $notab=0, $picto='')
//$links  // Tableau des onglets, appelé $head plus haut.
//$active // Onglet actif (mettre le nom de l'onglet défini dans votre fichier de module, ou un nom contenu dans $head[$h][2]). Cet onglet sera mis en surbrillance
//$title  // Title to show (shown into a special tab that you can't click)
//$notab
//$picto  // Name of image to show into title. Possible values are:
//            product
//            service
//            company

This function will show required tabs and open an html element < div class="" > that correspond to the area under the tabs. To close area of a tab, just use < /div > into your PHP page.

PHP 画面の作成や更新 (任意)

使用場面: モジュールの目的が、画面の新規作成または変更を必要とする機能の追加である場合.

新規 PHP 画面の作成

次に、 modulebuilder/myobject_page.php ディレクトリに例として提示されているスケルトンテンプレートを使用して、テーブルのデータを表示/編集するPHPページを作成する必要がある (コマンドラインからのスクリプト開発については、 Script development を参照).

新しいユーザー画面を作成するには、htdocs のサブディレクトリを作成し(まだ作成されていない場合)、作成するページを保存するために、モジュール(例えば、htdocs/mymodule )のサブディレクトリを作成する.

そのディレクトリに、ページファイルの出発点となるファイル myobject_page.php をコピーする。. main.inc.phpファイルへの相対パスが正しくなるようにファイルを編集する.

// Load Dolibarr environment
$res=0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include($_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php");
// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1;
while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; }
if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include(substr($tmp, 0, ($i+1))."/main.inc.php");
if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php");
// Try main.inc.php using relative path
if (! $res && file_exists("../main.inc.php")) $res=@include("../main.inc.php");
if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php");
if (! $res && file_exists("../../../main.inc.php")) $res=@include("../../../main.inc.php");
if (! $res) die("Include of main fails");

ご覧のように、main.inc.php(または master.inc.php)のロードは何回か試行される。目標は、大抵のケースで成功すること。最小は2行: master/main.inc.phpをdolibarrルートディレクトリにロードしようとする行と、モジュールが "custom "ディレクトリにデプロイされるケースをサポートするためにファイルをロードしようとする行。しかし、より多くの状況に対応するため、より多くを持つことができる。提供された例は、ほぼすべての状況/セットアップで main/master.inc.php ファイルをロードできるはず。

注意: モジュール・ディレクトリ・ツリーに対するファイルの深さによっては、さらに"../"を追加する。

main.inc.phpファイルでは、技術上の環境変数とパーミッションを読み込む。以下の変数はこのファイルに配置されているオブジェクト:

  • $user ユーザーの特徴とパーミッションを保持するオブジェクト。
  • $conf Dolibarrの設定を保持するオブジェクト
  • $db データベースへのオープンされた接続ハンドラを保持するオブジェクト。
  • $langs ユーザー言語を保持するオブジェクト。

次にページを表示するために自前コードを入力する.

  • モジュール専用クラスやライブラリをインクルードするには、(include_onceを直接使わず)Dolibarr関数を使う:

Example :

dol_include_once('/mymodule/class/myclass.class.php', 'MyClass');
  • Dolibarrで提供されているクラスをインクルードするには、以下の構文を使う:

Example :

require_once DOL_DOCUMENT_ROOT.'/core/class/doli.class.php';

Add some fields into existing forms

You may want to provide a module that adds more fields into forms (input and view) of some elements.

A heavy solution (but not so bad) may be to replace all pages used to create element (this means to disable the "New element" menu entry and adding yours, and disable tab that shows element to replace with a tab that is your own full page (copied/pasted from original) to do same than original page but modified to add your fields and stored added data into your own table). Go to menu #Define your entries in the menu (optional) and #The tab management (optional) if this solution suits you (this solution is more powerful since you can change everything you want into the page).

We will describe here another solution, that works only to "add fields" at end of existing fields, using the element "category" as an example but you can convert this tutorial for invoice, proposal ...

  • First thing is to add a table, owned by your module, to store the value of new fields. This table will have only one column called "rowid" (will contain the same value than field rowid of element table) + one column for each new field you want to add. Then create a class with CRUD (Create/Read/Update/Delete) methods for this new table. For this two tasks, go back to previous chapter #Create your SQL tables and the PHP DAO class.
  • Next step is to add a hook into your module to add the new fields into the form. See chapter Hooks_system#Implement_the_Hook for generic documentation to use hooks.

If you follow this tutorial, to be able to add fields into category forms, you must do:

En verysmall.png Page waiting to complete. To complete, create an account, go back and clic on "Modify".
Fr verysmall.png Page en attente d'être complété. Pour compléter, créez un compte, revenez et cliquez sur "Modifier".
Es verysmall.png Página a completar. Para completarla, cree una cuenta, vuelva a la página y haga clic en "editar"
De verysmall.png Seite wartet auf Vervollständigung. Um zu helfen, erstelle ein Konto, gehe zurück und klicke auf "Bearbeiten".
Cn verysmall.png 待完成,欲帮助完成,注册帐号,点击“编辑"
Jp verysmall.png ページは未完成の状態です。完成させるにはアカウントを作成し、ページに戻って「編集」をクリックして下さい。

Add/replace part of fields supported by hooks

See chapter Hooks_system#Implement_the_Hook to know how to use Dolibarr existing hooks to add/replace code at Dolibarr hooks place.

データベース アクセス

自前テーブルの中でデータベースのデータを編集する必要がある場合、前に生成されたPHPクラスを使うこと。

専用の PHP クラスがないテーブルにアクセスしたい場合 (たとえば、特定の結合やフィルタを使用したレコードの一覧を取得したい場合など) 、これはいつでも可能。この場合に、倣うべきコード例は:

操作が、 insert, update または delete:

$db->begin();   // Start transaction
$db->query("My SQL request insert, update or delete");
$db->commit();       // Validate transaction
or $db->rollback()  // Cancel transaction

操作が read:

$resql=$db->query("My select request");
if ($resql)
{
	$num = $db->num_rows($resql);
	$i = 0;
	if ($num)
	{
		while ($i < $num)
		{
			$obj = $db->fetch_object($resql);
			if ($obj)
			{
				// You can use here results
				print $obj->field1;
				print $obj->field2;
			}
			$i++;
		}
	}
}

Define style of your pages

To have the look of your own pages to match the Dolibarr theme, it is necessary to use the Dolibarr CSS styles.

You can use for example:

  • class="liste_titre" on tags tr and td for the head row of a table.
  • class="pair" or class="impair" on tags tr and td of other rows of a table.
  • class="flat" on all input fields (input, select, textarea...).
  • class="button" on HTML fields with type input type="submit".

Use the Dolibarr date picker

If you want to use the Dolibarr date selector (with its calendar popup) into your pages, use the following line:

 $form=new Form($db);
 $form->select_date('','mykey',0,0,0,"myform");

The string mykey will identify the date selector in the form. You must use different values if you use several date selectors in same page. The string myform is the name of the FORM in which the selector is included (value found in the form name="myform" in HTML page). This means a date selector must be included necessarily into an html FORM.

To get value after the POST of your form, the command is:

$mydate = dol_mktime(12, 0 , 0, $GETPOST('mykeymonth', 'int'), GETPOST('mykeyday', 'int'), GETPOST('mykeyyear', 'int'));
print strftime('%A %d %B %Y', $mydate);

Overwrite template file (tpl)

If you want to overwrite tpl file on your module, you need to declare it on the module_parts :

'tpl' => 1,

Then you can put any tpl file on mymodule/core/tpl as soon as the module is activate, the tpl will be overwrited

自前の準備ページを追加 (任意)

When: If your module needs parameters, which are to be provided by the user, for proper setting up of the module.

Create your page to edit parameters

If your module needs several parameters to be setup, you must create a page to edit options (these options will be saved in the table llx_const). Create a page named mymodule_setuppage.php that shows a form for possible options to update them into the above-mentioned table. It is necessary to take an example from a page of the directory /admin that will show you the way to read/save your parameters. Put this PHP page into the directory /admin of your module (e.g. mymodule/admin/mymodule_setuppage.php).

Modify the descriptor file of your module

Then, within the descriptor file of your module, modify the variable config_page_url to set the name of this PHP page. If the page is in the directory admin/, then the path is not required, e.g. like this:

$this->config_page_url = array("mymodule_setuppage.php");

If the page is in the directory mymodule/admin/, then like this:

$this->config_page_url = array("mymodule_setuppage.php@mymodule");

Test your page

Go into page Home->Setup->Modules, you should see a picture at the end of the line of your module to reach your setup page. Click on it, you should be able to view/edit parameters from your page.

メニューに自前項目を定義 (任意)

When: If you have created PHP pages, it is necessary that those pages can be reached from menu entries in Dolibarr menu.

Define your menu entries

For this, you must define into the module descriptor, the array this->menu that declares all menus added by your module. This array contains entries that will appear once your module is activated. The example module descriptor file modMyModule.class.php contains an example to declare a top menu and also its left menu entries.

This is the example of code to declare your own menu entries in a module descriptor file:

// Main menu entries
$this->menu = array();			// List of menus to add
$r=0;

// Add here entries to declare new menus
// Example to declare the Top Menu entry:
$this->menu[$r]=array(	'fk_menu'=>0,			// Put 0 if this is a top menu
			'type'=>'top',			// This is a Top menu entry
			'titre'=>'MyModule top menu',
			'mainmenu'=>'mymodule',
			'leftmenu'=>'mymodule',
			'url'=>'/mymodule/pagetop.php',
			'langs'=>'mylangfile',	// Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
			'position'=>100,
			'enabled'=>'1',			// Define condition to show or hide menu entry. Use '$conf->mymodule->enabled' if entry must be visible if module is enabled.
			'perms'=>'1',			// Use 'perms'=>'$user->rights->mymodule->level1->level2' if you want your menu with a permission rules
			'target'=>'',
			'user'=>2);				// 0=Menu for internal users, 1=external users, 2=both
$r++;

// Example to declare a Left Menu entry:
$this->menu[$r]=array(	'fk_menu'=>'fk_mainmenu=xxx',		    // Use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode of parent menu
			'type'=>'left',			        // This is a Left menu entry
			'titre'=>'MyModule left menu 1',
			'mainmenu'=>'xxx',
			'leftmenu'=>'yyy',
			'url'=>'/mymodule/pagelevel1.php',
			'langs'=>'mylangfile',	// Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
			'position'=>100,
			'enabled'=>'1',			// Define condition to show or hide menu entry. Use '$conf->mymodule->enabled' if entry must be visible if module is enabled.
			'perms'=>'1',			// Use 'perms'=>'$user->rights->mymodule->level1->level2' if you want your menu with a permission rules
			'target'=>'',
			'user'=>2);				// 0=Menu for internal users,1=external users, 2=both
$r++;

To show the menu or not depending on a permission, modify property perms in the array. See chapter on permissions later to see how to add permissions.

Test your menu entries

Disable and re-enable your module under the Dolibarr module setup page, menus entries must appear (if property 'enabled' is declaration array is ok).

自前の許認可を追加 (任意)

When: If you want to add new permissions.

The way to define permissions that will manage your module is done inside the module descriptor created previously. Modify line

$this->rights_class = 'mymodule'

with correct value for mymodule.

Then you must fill the array $this->rights with as many entries than different permissions you need to manage.

$this->rights[$r][0] = 10001;
$this->rights[$r][1] = 'Label by default of permission';
$this->rights[$r][2] = 'r';
$this->rights[$r][3] = 1;
$this->rights[$r][4] = 'action';
$this->rights[$r][5] = 'subaction';
$r++;

Into $this->rights[$r][0], put a permission id not already used (See into menu System info on a working installation of Dolibarr to know list of id already used by standard modules. Into $this->rights[$r][1], put a label by default for permission (This label will be used if no translation can be found into the file admin.lang Translation key should be "Permission10001=My permission Label"). Into $this->rights[$r][2], types of the permission. There are three type of permission, 'r' for read, list or expert permission, 'w' for write or update permission and 'd' for delete permission. Into $this->rights[$r][3], put 1 if this permission must be granted automatically by default to any newly created user. Into $this->rights[$r][4] and $this->rights[$r][5], put an action and subaction string without spaces. You will be able to test if a user has the permission in your PHP source code with the sequence:

if ($user->rights->mymodule->action->subaction) ...

自前の box を定義 (任意)

When: If your module needs to provide one or several new boxes to show on home page.

Define your box

For this, modify the array $this->boxes into the module descriptor file. All you have to do is to add 2 lines for each box file you will create into directory htdocs/mymodule/core/boxes

Example:

$this->boxes[0]['file']='mybox0.php@mymodule'
$this->boxes[0]['note']='My box 0'
 ...
$this->boxes[n]['file']='myboxn.php@mymodule'
$this->boxes[n]['note']='My box n'

Then create files htdocs/mymodule/core/boxes/mybox0.php, htdocs/mymodule/core/boxes/mybox1.php... by copying an example from an existing box file (found into directory htdocs/core/boxes).

Test if your box is detected by Dolibarr

Disable and enabled module.

Go into menu Home - Setup - Boxes.

Your boxes must appear in the list of boxes you can activate. Activate the box and go on the home page to see if the box is showing correctly.

自前のエキスポートを定義 (任意)

When: If your module provides new predefined database export profiles (for its own tables or for already existing tables of another module).

Define export

For this uncomment and modify arrays $this->export_xxx in your module descriptor file.

Test your export

Go into menu Tools -> Export. Your export will appear in the list of available predefined exports (if your module is enabled). Choose it, you must see a list of all possible fields defined in the export arrays. Choose on field and try to build an export file. If ok, try again with all fields.

自前の CSS スタイルを定義 (任意)

When: If in your PHP pages, you use class styles that are not defined inside Dolibarr themes CSS (not recommanded).

Create and declare your style sheet

Create a style sheet CSS named mymodule.css or mymodule.css.php and put it into directory htdocs/mymodule. You can have several CSS files per module. Remember it's better to use existing styles already available by default into Dolibarr (The CSS file used by Dolibarr is file themes/mytheme/themename.css.php. Create your own CSS files only if you need absolutely to add not already existing styles.

Once your style sheets are ready, declare them into your module descriptor file by modifying the property $this->modules_parts. Value to put here must be an array of relative URLs to your CSS files. For example

$this->module_parts = array('css' => array('/mymodule/css/mymodule.css.php','/mymodule/css/myother.css'));

Test your style sheet

Disable and enable your module.

Go on the home page (index.php). Show the HTML source of the page.

You should see into the HTML header, a line that declares your style sheet.

自前の Javascript 関数を追加 (任意)

When: If in your PHP pages, you use javascript functions not available in Dolibarr (in file lib_head.js)

If you need to use your own javascript functions inside your PHP pages, it is necessary to have your functions, defined into your javascript file htdocs/mymodule/js/mymodule.js, included into the HTML HEAD section. To ask Dolibarr that forge this header to include your own javascript file, you must just provide it to the llxHeader() function called by your page.

Example for page /htdocs/mymodule/mypage.php :

$morejs=array("/mymodule/js/mymodule.js");
llxHeader('','Titre','','','','',$morejs,'',0,0);

いずれかの Dolibarr イベントで自前コードを実行する (任意)

When: If you want to execute your own code once a common Dolibarr event has occurred (example: I want to update a table in my module when an invoice is created into Dolibarr), you must create a triggers.

See also Interfaces_Dolibarr_toward_foreign_systems and Interfaces_from_foreign_systems_toward_Dolibarr

Dolibarr フックポジションの内部に、自前コードを挿入 (任意)

When: When you want to add code or replace Dolibarr code into another situation than a business event (See the previous chapter for adding code during a business event).

See page Hooks_system.


自前の番号付けルールを追加

When: When you need a new rule for generated ref of elements that are not covered by existing rules.

See page Create numbering module.

自前の文書テンプレートを追加 (任意)

When: When you want to personalized your own generated PDF or ODT documents.

Note: To add this feature you don't need to create a module descriptor.

Documentation to add your own template is available on page Create_a_PDF_document_template or Create_an_ODT_document_template.

自前のスキンを追加 (任意)

When: When you want to personalized your colors/fonts/images.

Note: To add this feature you don't need to create a module descriptor.

To add your own skin, read page Skins.

コーディングルールおよび定義済み関数

The coding rules to be followed are defined in the Developer documentation, under section "General Information - Language and standards development".

A lot of predefined features for developers are also available and described into page Developer documentation under section "Technical components of Dolibarr".

自前モジュールを配布し導入するためのパッケージを作成

This process must be used to generate a package to submit it on the http://www.dolistore.com marketplace. But you can use it to have a package easy to distribute on your own network.

  • Go into the directory /build and copy the file makepack-dolibarrmodules.conf into makepack-mymodule.conf. Warning, this directory may not be provided in some packages of stable versions. If so, it can be retrieved from the snapshot available for download on the Dolibarr website in area "Development version" (taken in this case the whole build directory which is autonomous and independent directory).

Edit this file to add a list of file names for all new files you created for your module (module descriptor, new sql tables files, php page, images, etc...)

  • Run the script via Perl (need the Perl version 5.0 or later):
perl makepack-dolibarrmodule.pl

The script asks you the name of your module, its major and minor version. A file mymodule.zip will then be manufactured containing your module ready to be deployed.

  • The person who receives your module must then place the file in the root directory of a Dolibarr installation and perform the command:
tar -xvf mymodule.zip
  • If you want your module to be public, you can submit it (the zip file) on Dolibarr marketplace website: DoliStore.com (you must create an account first and be logged to use the link "Submit a module/product").
    • If your module was built correctly, the file will be validated later.
    • If quality is enough and license permits it, the code might be added inside main Dolibarr sources (except if you disagree for that).

DoliStore での外部モジュール 有効化/活性化 条件

See Validation Rules