Can You Make a Custom Field with multiple columns? I have a custom field where I'm defining AttributeType::Mixed in order to achieve the affect of saving multiple pieces of data for a single field. The data gets stored as JSON as expected. Quick example shown below:

public function defineContentAttribute()
{

    return AttributeType::Mixed;

}


I was wondering though, is it possible to define multiple columns for a single field? If so will the field then require its own table? Not sure where to begin with this one.

Thanks for any assistance.
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-&gt;element will give you access access to the Element Model  
  // your field is associated with (For example, EntryModel, CategoryModel, etc).

  // $this-&gt;model will give you access access to the FieldModel 
  // your field is associated with.

  // craft()-&gt;request-&gt;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()-&gt;customPlugin-&gt;getCustomFieldValues();

    return craft()-&gt;templates-&gt;render('customplugin/fields/input', array(
        'name'       =&gt; $name,
        'values'     =&gt; $values
    ));
}