Many to many relation in administration area
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); ?>