Create components
Confetti makes it quick and easy to create custom components. This allows you to build your own CMS by combining reusable components. These components can be easily copied into your next project. The simplest way to create a component is to copy an existing one and modify it.
A component consists of at least three files. Let’s create a ColorComponent
for example. The key file is /Components/ColorComponent.php
. Several methods are mandatory:
The type()
method defines the type of the component.
public function type(): string
{
return 'color';
}
This allows you to use the component in your Blade views as follows:
<div style="color: {{ $banner->color('background_color') }}"/>
The get()
method retrieves the saved value, which may not always be a string. To handle other data types, you can override the __toString()
method to convert the returned value into a usable format.
public function get(): ?string
{
// Retrieve the saved value
$value = $this->contentStore->findOneData($this->parentContentId, $this->relativeContentId);
if ($value !== null) {
return $value;
}
return '#ffffff';
}
Because the __toString()
method calls the get()
method, you don't need to use the ->get()
method in your Blade file.
This method returns the full path to the Blade file used for the admin input view.
/**
* Returns the full path to the Blade input file.
*/
public function getViewAdminInput(): string
{
return 'admin.components.color.input';
}
This method returns the full path to the MJS file used for the admin preview view.
/**
* Returns the full path to the preview MJS file.
*/
public static function getViewAdminPreview(): string
{
return '/admin/components/color/preview.mjs';
}
You can also create "decoration" methods. These allow you to add options to your component in the view (HTML for the front-end).
public function default(string $default): self
{
$this->setDecoration('default', ['default' => $default]);
return $this;
}
This enables usage like:
<div style="color: {{ $banner->color('background_color')->default('#ff0000') }}"/>
Decorations can be read in both PHP and JavaScript.
You can read decorations in the get()
method:
public function get(): ?string
{
// Retrieve the saved value
$value = $this->contentStore->findOneData($this->parentContentId, $this->relativeContentId);
if ($value !== null) {
return $value;
}
return $this->getDecoration('default', 'default') ?? '#ffffff';
}
Decorations can also be read in the JavaScript preview file:
constructor(id, value, component) {
this.id = id;
this.value = value || component.decorations.default?.default || null;
}