Skip to content
Milan Ricoul edited this page Sep 16, 2024 · 6 revisions

ACF Block Class

For better readability, place your ACF blocks in an Acf sub-folder in classes/Blocks.

  1. Create your Acf block class
// Acf Block Example
namespace BEAPI\Blocks\Acf;

use BEAPI\Blocks\Acf_Json_Block;

class Block_Example extends Acf_Json_Block {
	/**
	 * Get slug
	 *
	 * @return string
	 */
	public function get_slug(): string {
		return 'offices';
	}

	/**
	 * Return block data
	 *
	 * @param array $block
	 * @param string $content
	 * @param bool $is_preview
	 * @param int $post_id
	 *
	 * @return array
	 */
	public function get_block_data( array $block, $content = '', $is_preview = false, $post_id = 0 ): array {
		$data = parent::get_block_data( $block, $content, $is_preview, $post_id );

		return wp_parse_args(
			[
				'block_offices' => get_field( 'offices_items', $block['id'] ),
				'block_title'   => get_field( 'offices_title', $block['id'] ),
			],
			$data
		);
	}

	/**
	 * Validate block
	 *
	 * @param array $block
	 * @param $content
	 * @param $is_preview
	 * @param $post_id
	 *
	 * @return \WP_Error
	 */
	public function validate( array $block, $content = '', $is_preview = false, $post_id = 0 ): \WP_Error {
		$errors = new \WP_Error();
		if ( empty( get_field( 'block_title', $block['id'] ) ) ) {
			$errors->add( '', 'Vous devez contribuer un titre.' );
		}

                return $errors;
	}
}
  1. Create the block.json file in assets/blocks/offices/ plugin's folder. Rename the offices folder with the name of the block defined in get_slug() method from the class and add the following JSON schema example below.
{
	"$schema": "https://advancedcustomfields.com/schemas/json/main/block.json",
	"name": "sample-blocks/offices",
	"title": "Offices",
	"description": "Display a list of offices.",
	"category": "formatting",
	"icon": "folder",
	"acf": {
		"mode": "auto"
	},
	"supports": {
		"align": false
	},
	"attributes": {
		"align": {
			"type": "string",
			"default": "full"
		}
	},
	"textdomain": "sample-blocks",
	"editorStyle": "sample-blocks-hero-front-page-editor-style",
	"editorScript": "sample-blocks-hero-front-page-editor-script",
	"style": "sample-blocks-hero-front-page-style",
	"viewScript": "sample-blocks-hero-front-page-script"
}

For more informations about the block.json content, see the official documentation.

  1. Allow to register your block in Blocks.php class
public function register_blocks(): void {

		/**
		 * Here enter all the blocks class names you need to instantiate
		 * This have to be instances of \BEA\PB\Block_Interface
		 */
		$blocks = [
			\BEA\PB\Block_Interface\Blocks\Acf\Block_Example::class,
		];

		$blocks = apply_filters( 'bea_pb_blocks', $blocks );

		array_map(
			static function ( string $block ) {
				/* @var $klass Block_Interface */
				$klass = new $block();
				$klass->init();
			},
			$blocks
		);

		$this->allow_custom_blocks( $blocks );
	}

Methods

get_slug

This method is required to register your block. A unique name that identifies the block (without namespace). For example ‘offices’. Note: A block name can only contain lowercase alphanumeric characters and dashes, and must begin with a letter.

Example

        public function get_slug(): string {
		return 'offices';
	}

get_block_args

This method is required to parse with default args. Array of arguments for registering a block type.

If you want to apply a default configuration on all your ACF blocks, you can modify this default args ( https://github.com/BeAPI/bea-plugin-boilerplate/blob/master/classes/Blocks/Acf_Block.php#L43 ) to modify category for example.

[
				'title'    => $this->get_slug(),
				'category' => 'common',
				'mode'     => 'auto',
				'example'  => [
					'attributes' => [
						'mode' => 'preview',
						'data' => [
							'is_preview' => true,
						],
					],
				],
			]

Example to override title in my block

	public function get_block_args(): array {
		return [
			'title' => 'Offices list',
		];
	}

get_block_data

This method is the most important, all data recovery must be done in this method which will inject the data into the template. All custom code, calculations, etc. should be located here. No custom code should be in your template.

Example

	public function get_block_data( array $block, $content = '', $is_preview = false, $post_id = 0 ): array {
		$data = parent::get_block_data( $block, $content, $is_preview, $post_id );

		return wp_parse_args(
			[
				'block_subtitle'          => get_field( 'block_subtitle', $block['id'] ),
				'block_title'             => get_field( 'block_title', $block['id'] ),
				'block_content'           => get_field( 'block_content', $block['id'] ),
				'block_product_link'      => get_field( 'block_product_link', $block['id'] ),
				'block_solution_link'     => get_field( 'block_solution_link', $block['id'] ),
				'block_bg_image'          => get_field( 'block_image', $block['id'] ),
				'block_background_enable' => get_field( 'block_background_enable', $block['id'] ),
			],
			$data
		);
	}

validate

This method is used to check the mandatory fields for the contributor and display an error in the back office.

Example

	public function validate( array $block, $content = '', $is_preview = false, $post_id = 0 ): \WP_Error {
		$errors = new \WP_Error();
		if ( empty( get_field( 'block_title', $block['id'] ) ) ) {
			$errors->add( '', 'Title is required' );
		}

		$link_product = get_field( 'block_product_link', $block['id'] );
		if ( isset( $link_product['url'] ) && empty( $link_product['title'] ) ) {
			$errors->add( '', 'Label of CTA is required' );
		}

		return $errors;
	}

Templates

All block templates are located in the theme in /components/gutenberg/{plugin-name}/

Error template

The error template is used to display contribution errors in the back office. ( template-admin-block-invalid.php )

<?php
/**
 * @var \WP_Error $error_messages
 */

?>

<?php
if ( $error_messages->has_errors() ) :
	?>
	<div class="components-notice is-error">
		<div class="components-notice__content">
			<ul style="padding-left: 10px">
				<?php
				foreach ( $error_messages->get_error_messages() as $error_message ) :
					?>
					<li>
					<?php
						echo esc_html( $error_message );
					?>
						</li>
					<?php
				endforeach;
				?>
			</ul>
		</div>
	</div>
	<?php
endif;

Block Example Template

All the templates files are pre-fixed by block-xxxx.php

Example of block-offices.php

<?php
/**
 * Block Gouvernance
 *
 * -- Default data --
 *
 * @var string $id
 * @var string $block_id id attribute allowing for custom "anchor" value
 * @var bool $block_is_preview True during AJAX preview.
 * @var string $block_classname list of block classes
 * @var string $block_content The block inner HTML (empty).
 * @var int|string $block_post_id The post ID this block is saved to.
 *
 * -- Custom data --
 * @var string $block_title the title of block
 */

<section 
	id="<?php echo esc_attr( $block_id ); ?>" 
	class="block block--<?php echo esc_attr( $block_classname ); ?>">
	<div class="container">
           <?php echo esc_html($block_title); ?>
        </div>
</section>