Wiki

Clone wiki

WordPress Plugin Foundation / How to add a custom Form Field object

Your plugin may want to accept input beyond the default range of form fields. One way to accomplish this is to create a custom form field. In order for manifests in your plugin to use your custom form field, they need to be registered with the form field factory.

Once they're registered, your custom form fields will be available by everything that uses your form field container.

#!php

// This example is from the JDSDesigns Newsletter plugin

// assume this function returns a fully setup Pimple container
$container = getContainer(); 

// create a config array in the container for your custom field
$container['newsletter.fields.render_email.config_array'] = [];

// add the object to the container; remember to use a factory when appropriate
$container['Newsletter.Fields.RenderEmail'] = function($c) {
    return new \JDSDesigns\Newsletter\Fields\RenderEmail($c['newsletter.fields.render_email.config_array'], $c);
};

// register the new field with the FieldFactory class    
$field_factory = $container['FieldFactory'];

$field_factory->registerField('render_email', function($config_array = []) use ($container) {
    if ($config_array) {
        $container['newsletter.fields.render_email.config_array'] = $config_array;
    }
     return $container['Newsletter.Fields.RenderEmail'];
});

// The registered fields are per-object instance (not a class-wide static setup), but
// the Pimple container will return the same FieldFactory object whenever it is requested.

Updated