# Custom Field With a Custom Editor Component
`FIELD API` `EXTEND FIELDS`

A field built on [`BaseFieldManager`](/api/classes/base-field-manager/) can bring its own Vue components to the form editor: one that draws the field on the editor canvas, and one that edits its settings in the **Input Customization** panel.

This guide builds a field called `MyCustomElement` with both.

You need:

1. A PHP class that extends `BaseFieldManager` and names your components.
2. A script that registers the Vue components with the editor.
3. The two Vue components.

## The PHP class

```php
<?php

namespace MyPlugin\CustomFields;

use FluentForm\App\Services\FormBuilder\BaseFieldManager;
use FluentForm\Framework\Helpers\ArrayHelper as Arr;

class MyCustomElement extends BaseFieldManager
{
    /**
     * Wrapper class for the element
     * @var string
     */
    protected $wrapperClass = 'my_custom_element_wrapper';

    public function __construct()
    {
        parent::__construct(
            'my_custom_element', // Unique element key
            'My Custom Element', // Element title
            ['custom', 'element', 'advanced'], // Search tags
            'advanced' // Position (general/advanced)
        );

        // Add filter for response rendering
        add_filter('fluentform/response_render_' . $this->key, array($this, 'renderResponse'), 10, 4);
        add_filter('fluentform/validate_input_item_' . $this->key, array($this, 'validateInput'), 10, 5);
        
        // Enqueue custom editor assets
        add_action('fluentform/loading_editor_assets', function () {
            wp_enqueue_script(
                'my-custom-element-editor',
                MY_PLUGIN_URL . 'assets/js/custom-element.js',
                [],
                '1.0.0',
                true
            );
        });
    }

    function getComponent()
    {
        return [
            'index'          => 25, // Priority in the form editor
            'element'        => 'my_custom_element',
            'attributes'     => [
                'name'      => 'my_custom_element',
                'data-type' => 'my_custom_element'
            ],
            'settings'       => [
                'label'              => __('My Custom Element', 'my-plugin'),
                'admin_field_label'  => '',
                'custom_option'      => '',
                'conditional_logics' => [],
                'container_class'    => '',
                'custom_settings'    => [
                    'option_one' => '',
                    'option_two' => '',
                    'show_extra' => 'hide'
                ],
                'validation_rules'   => [
                    'required' => [
                        'value'   => false,
                        'message' => __('This field is required', 'my-plugin'),
                    ],
                ],
            ],
            'editor_options' => [
                'title'         => __('My Custom Element', 'my-plugin'),
                'icon_class'    => 'el-icon-s-operation',
                'template'      => 'CustomEditorField', // IMPORTANT: Must be 'CustomEditorField' to use custom Vue components
                'componentName' => 'MyCustomElementEditor', // IMPORTANT: Must match the Vue component name in JavaScript
            ],
        ];
    }

    public function getGeneralEditorElements()
    {
        return [
            'label',
            'label_placement',
            'admin_field_label',
            'custom_option',
            'custom_settings', // This will use the custom settings component
            'validation_rules',
        ];
    }

    public function getAdvancedEditorElements()
    {
        return [
            'container_class',
            'name',
            'conditional_logics'
        ];
    }

    public function getEditorCustomizationSettings()
    {
        return [
            'custom_option' => [
                'template' => 'selectGroup',
                'label'    => __('Custom Option', 'my-plugin'),
                'options'  => [
                    [
                        'value' => 'option1',
                        'label' => __('Option 1', 'my-plugin')
                    ],
                    [
                        'value' => 'option2',
                        'label' => __('Option 2', 'my-plugin')
                    ],
                    [
                        'value' => 'option3',
                        'label' => __('Option 3', 'my-plugin')
                    ]
                ]
            ],
            'custom_settings' => [
                'template'      => 'CustomSettingsField', // IMPORTANT: Must be 'CustomSettingsField' to use custom Vue components
                'label'         => __('Custom Settings', 'my-plugin'),
                'componentName' => 'MyCustomSettingsComponent' // IMPORTANT: Must match the Vue component name in JavaScript
            ],
        ];
    }

    /**
     * Render the element on the frontend
     * @param array $data Element data
     * @param object $form Form object
     * @return void
     */
    public function render($data, $form)
    {
        $elementName = $data['element'];

        // Add default class
        $data['attributes']['class'] = trim('ff-el-form-control ' . Arr::get($data, 'attributes.class', ''));
        $data['attributes']['id'] = $this->makeElementId($data, $form);
        
        // Add tab index if available
        if ($tabIndex = \FluentForm\App\Helpers\Helper::getNextTabIndex()) {
            $data['attributes']['tabindex'] = $tabIndex;
        }

        // Set aria-required attribute
        $ariaRequired = Arr::get($data, 'settings.validation_rules.required.value') ? 'true' : 'false';
        
        // Get custom settings
        $customOption = Arr::get($data, 'settings.custom_option');
        $showExtra = Arr::get($data, 'settings.custom_settings.show_extra', 'hide') === 'show';
        
        // Enqueue frontend assets if needed
        wp_enqueue_script(
            'my-custom-element-frontend',
            MY_PLUGIN_URL . 'assets/js/custom-element-frontend.js',
            ['jquery'],
            '1.0.0',
            true
        );
        
        // Create element markup
        $elMarkup = '<div class="my_custom_element_container">';
        $elMarkup .= '<input ' . $this->buildAttributes($data['attributes'], $form) . ' aria-required="' . $ariaRequired . '">';
        
        if ($showExtra) {
            $elMarkup .= '<div class="extra_content">Extra content is visible</div>';
        }
        
        $elMarkup .= '</div>';
        
        // Build final HTML
        $html = $this->buildElementMarkup($elMarkup, $data, $form);
        
        // Output the HTML
        echo apply_filters('fluentform/rendering_field_html_' . $elementName, $html, $data, $form);
    }

    /**
     * Format the field value for display in entries, emails, etc.
     * @param mixed $data Field value
     * @param array $field Field settings
     * @param int $form_id Form ID
     * @param bool $isHtml Whether HTML output is expected
     * @return string
     */
    public function renderResponse($data, $field, $form_id, $isHtml)
    {
        if (is_array($data)) {
            return implode(', ', $data);
        }
        
        return $data;
    }

    /**
     * Validate the field input
     * @param array $errorMessage Error message array
     * @param array $field Field settings
     * @param array $formData Form data
     * @param array $fields All form fields
     * @param object $form Form object
     * @return array
     */
    public function validateInput($errorMessage, $field, $formData, $fields, $form)
    {
        $fieldName = $field['name'];
        if (empty($formData[$fieldName])) {
            return $errorMessage;
        }
        $value = $formData[$fieldName]; // This is the user input value
        
        // Add your custom validation logic here
        
        return $errorMessage;
    }
}
```

Two settings connect the PHP class to your Vue components:

- In `getComponent()`, `editor_options.template` set to `CustomEditorField` tells the editor to draw the field with your component, and `editor_options.componentName` names it.
- In `getEditorCustomizationSettings()`, a setting with `template` set to `CustomSettingsField` is edited with your component, and its `componentName` names it.

Each `componentName` must match the key you register in JavaScript, letter for letter. If it doesn't, the editor shows nothing for that part.

## Register the components

```javascript
// custom-element.js

import MyCustomElementEditor from './components/MyCustomElementEditor.vue';
import MyCustomSettingsComponent from './components/MyCustomSettingsComponent.vue';

// Register the components with EXACTLY the same names used in PHP
window.ffEditorOptionsCustomComponents = window.ffEditorOptionsCustomComponents || {};

// IMPORTANT: These keys must match the componentName values in PHP
window.ffEditorOptionsCustomComponents.MyCustomElementEditor = MyCustomElementEditor;
window.ffEditorOptionsCustomComponents.MyCustomSettingsComponent = MyCustomSettingsComponent;
```

The editor runs Vue 2, so write the components with the Options API. Build this file with a bundler that compiles Vue 2 single-file components, such as webpack with `vue-loader` 15 or Vite with `@vitejs/plugin-vue2`, and enqueue the built file.

Enqueue it on `fluentform/loading_editor_assets`, as the class above does. That hook runs before the editor's own script is queued, so your components are registered before the editor draws the form.

## The canvas component

The editor draws the field on the canvas with this component. It receives:

- `item`: the field, including its `settings`.

```vue
<!-- MyCustomElementEditor.vue -->
<template>
  <div class="my-custom-element-editor">
    <h3>My Custom Element Editor</h3>
    <!-- Add your custom editor UI here -->
  </div>
</template>

<script>
export default {
  // IMPORTANT: This name must match the componentName in PHP
  name: 'MyCustomElementEditor',
  props: ['item'],
  mounted() {
    // The field data is available in this.item
    // Do your initialization work here
  }
}
</script>
```

## The settings component

The **Input Customization** panel uses this component for the `custom_settings` setting. It receives:

- `listItem`: the setting's definition from `getEditorCustomizationSettings()`.
- `editItem`: the field being edited. Change `editItem.settings` and the form saves it.
- `form_items`: every field in the form.

```vue
<!-- MyCustomSettingsComponent.vue -->
<template>
  <div class="my-custom-settings">
    <!-- Add your custom settings UI here -->
    
    <!-- Example settings -->
    <el-form-item label="Option One">
      <el-input v-model="editItem.settings.custom_settings.option_one" 
                placeholder="Enter Option One"></el-input>
    </el-form-item>
    
    <el-form-item label="Option Two">
      <el-input v-model="editItem.settings.custom_settings.option_two" 
                placeholder="Enter Option Two"></el-input>
    </el-form-item>
    
    <el-form-item>
      <el-checkbox v-model="editItem.settings.custom_settings.show_extra" 
                   :true-label="'show'" 
                   :false-label="'hide'">
        Show Extra Content
      </el-checkbox>
    </el-form-item>
  </div>
</template>

<script>
export default {
  // IMPORTANT: This name must match the componentName in PHP
  name: 'MyCustomSettingsComponent',
  props: ['listItem', 'editItem', 'form_items'],
  mounted() {
    // Initialize settings if they don't exist
    if (!this.editItem.settings.custom_settings) {
      this.$set(this.editItem.settings, 'custom_settings', {
        option_one: '',
        option_two: '',
        show_extra: 'hide'
      });
    }
  }
}
</script>

<style>
.my-custom-settings {
  padding: 10px;
}
</style>
```

Use `$set` when you add a property that wasn't there before, so Vue tracks it.

## Load the field

```php
<?php
// In your plugin's main file or a separate file

add_action('fluentform/loaded', function () {
    require_once 'path/to/MyCustomElement.php';
    new \MyPlugin\CustomFields\MyCustomElement();
});
```

## If the components don't show

1. Check the browser console for errors, and the Network tab for your script.
2. Run `Object.keys(window.ffEditorOptionsCustomComponents)` in the console on the editor page. Your component names should be listed.
3. Compare each name with the `componentName` values in PHP.
