If your custom field needs more than the default column to store it's data you can create your own custom table (or tables) and store your data however you need to.
This involves a few things:
- Create a Record that defines your database table
- Save the data to the custom table
- Retrieve the data from the custom table
Create a Record that defines your database table
To create a Record, take a look at the Craft Records documentation. The Record defines the columns in your database table and that custom table will get created when you install your plugin, and removed when you uninstall your plugin. So, after you create your Record, go ahead and re-install your plugin to get the database table to appear in the database and ensure it's the schema you need.
Save the data to the custom table
Now that you have your custom table, you can save data to it. In your Fieldtype Class CustomPlugin_CustomFieldType.php
you can do so using the onAfterElementSave()
method.
public function onAfterElementSave()
{
// $this->element will give you access access to the Element Model
// your field is associated with (For example, EntryModel, CategoryModel, etc).
// $this->model will give you access access to the FieldModel
// your field is associated with.
// craft()->request->post will give you access to the post data
// submitted on the request.
// Once you have retrieved and modified the data you want to save,
// you can go ahead and save it to your custom table
}
Retrieve the data from the custom table
To populate your field, you'll retrieve your data from your custom tables in the getInputHtml()
method. In the example below, I'm using calling the getCustomFieldValues()
method from the service layer which would query the database and give me back the data I need to hand off to my template to display:
public function getInputHtml($name, $value)
{
$values = craft()->customPlugin->getCustomFieldValues();
return craft()->templates->render('customplugin/fields/input', array(
'name' => $name,
'values' => $values
));
}