Writing a block
A block is a class with fields and a Blade view; this is how to write one that is edited in place.
A block is a class extending Mainstay\Content\Block, with fields as a content type has, drawn by the Blade view named after its handle: Note by blocks.note, CodeSample by blocks.code_sample. A type lists it in its #[Blocks], and from then on it can be added to a page.
The class
namespace App\Blocks;
use Mainstay\Content\Block;
use Mainstay\Content\Description;
use Mainstay\Content\Example;
use Mainstay\Content\Icon;
use Mainstay\Fields\Textarea;
#[Icon('quote')]
#[Description('A line the reader should not miss, set apart in the accent colour.')]
#[Example(['text' => 'Mainstay is not released yet.'])]
class Note extends Block
{
#[Textarea(required: true)]
public string $text;
}
#[Icon] names one of the admin's icons, block, paragraph, heading, quote, code, list, grid, columns, banner, image, gallery, video, star, book, table, link, button, calendar, pin, mail, person, chat and a few more, or an SVG of your own with #[Icon(file: 'icons/hero.svg')]. #[Description] is the sentence under its name in the Add block dialog, and #[Example] the values it is previewed with there. A block with no example is shown by its icon, its name and its description, if it has one.
The view
<div class="note">
<p>@field($block, 'text')</p>
</div>
@field($block, 'text') prints the field escaped, as {{ $block->text }} would. In the admin's Content tab it also marks the text, so an editor types it in place on the page. It takes Text and Textarea fields; any other field is edited in the block's settings and printed as the view likes.
Blocks inside a block
A block names the blocks it holds with #[Blocks], as a type does, and text: true lets it hold headings and paragraphs among them. The view prints them with @inner($block), in their order:
#[Blocks([Feature::class], text: true)]
class Features extends Block {}
<section class="features">@inner($block)</section>
@inner must be the only thing in the element it sits in: in the editor that element becomes where the inner blocks are added and moved. $block->inner() lists the blocks inside it, for a view that needs to count them or draw a list of their titles.
Things to know
Mainstay::marking()says whether the view is being drawn for the editor, for a view that has to show an empty field to be typed into.An image field on a block prints with
picture()and marks itself, so it is picked and replaced on the page.A field added to a block already in use needs a default, or a nullable property: the blocks stored before it do not have it.
Every block has an
id, given when it is first written and kept, for a view that needs one in its markup.