Documentation 2.x and 3.x

Many to many relation in administration area

Many to many relation

Common use case of many to many relation is categories. If you like the your products to appear on more than one category, you need to have many to many relationship.

In this example we will take similar task. We will use AddressBook plugin (described earlier) and add field Options where you can select many options from another table.

How to do that

We have taken AddressBook plugin and created custom field (read how to create custom fields). That custom field class is called elementOptions. It carry all operations to external table. When we create new record, it pulls all available fields from options table and generates checkbox. On save, it binds current record to options table (third table record_to_option is used).

See complete example:

How to use it in your project

Just copy element_options.php file to your plugin directory and add it to area class like that:

<?php
require_once(__DIR__.'/element_options.php');

$element = new ElementOptions(
array(
'title' => 'Options', //Field name
'showOnList' => true, //Show field value in list of all records
'previewLength' => 50,
'searchable' => true,

'optionTable' => 'm_examples_address_book2_option', //available options table
'optionValueField' => 'title', //options table value field
'optionIdField' => 'id', //options table id field
'recordToOptionTable' => 'm_examples_address_book2_record_to_option', //record to option many to many relation table
'recordToOptionRecordReference' => 'record_id', //reference field to record
'recordToOptionOptionReference' => 'option_id', //reference field to option
)
);
$this->addElement($element);

?>

Comments (1)

V

V

Hi, Great job. I might be wrong but just noticed that the file script.php in both install and uninstall has the wrong namespace. it should be
namespace Modules\examples\address_book2; instead of
namespace Modules\examples\address_book;

Write a comment

You must be logged in to comment.