In order to include a custom field type you first need to register your own module or plugin you can create the basic structure for both from pluginfactory.io and register them as you like. There is also a default module that comes with every Craft 3 installation. You only need to bootstrap it in your app.php
Then in your module you need the following code
public function init()
{
Event::on(Fields::class, Fields::EVENT_REGISTER_FIELD_TYPES, function(RegisterComponentTypesEvent $event) {
$event->types[] = MyField::class;
});
}
And your class could look like the Incognito Field for example.
Basically every field has several methods implemented in the FieldInterface
such as getInputHtml
to render the HTML or normalizeValue
to create a field value based on user or DB input and serializeValue
to prepare the value for your DB. The interface has everything you need.
A good example to get started is to extend the PlainText
field and customize it's functions. You can overwrite the inputHtml
function and render a custom template
public function getInputHtml($value, ElementInterface $element = null): string
{
// Get our id and namespace
$id = Craft::$app->getView()->formatInputId($this->handle);
$namespacedId = Craft::$app->getView()->namespaceInputId($id);
// Render the input template
return Craft::$app->getView()->renderTemplate(
'module-id/fields/hidden/_input',
[
'name' => $this->handle,
'value' => $value,
'field' => $this,
'id' => $id,
'namespacedId' => $namespacedId,
]
);
}