<?php
/**
* AgentForms Gutenberg Block
*
* Registers a custom block for the WordPress block editor (Gutenberg).
* Provides a Token field and optional Theme/Success Message overrides.
*
* Block JSON registration, server-side render callback, and editor script.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Register the Gutenberg block.
*/
function agentforms_register_block() {
register_block_type( 'agentforms/agentforms', array(
'style' => 'agentforms-style',
'script' => 'agentforms-gutenberg',
'editor_script' => 'agentforms-gutenberg-editor',
'render_callback' => 'agentforms_block_render',
) );
}
add_action( 'init', 'agentforms_register_block' );
/**
* Enqueue Gutenberg editor scripts.
*/
function agentforms_enqueue_block_editor_assets() {
wp_enqueue_script(
'agentforms-gutenberg-editor',
AGENTFORMS_PLUGIN_URL . 'assets/af-gutenberg.js',
array( 'wp-blocks', 'wp-element', 'wp-components', 'wp-editor' ),
AGENTFORMS_VERSION,
false
);
wp_enqueue_style(
'agentforms-gutenberg-editor',
AGENTFORMS_PLUGIN_URL . 'assets/af-gutenberg.css',
array(),
AGENTFORMS_VERSION
);
}
add_action( 'enqueue_block_editor_assets', 'agentforms_enqueue_block_editor_assets' );
/**
* Server-side render callback for the block.
*
* Delegates to the shortcode handler since it does all the heavy lifting.
*
* @param array $attributes Block attributes.
* @param string $content Block inner content.
* @return string Rendered form HTML.
*/
function agentforms_block_render( $attributes, $content = '' ) {
$token = isset( $attributes['token'] ) ? sanitize_text_field( $attributes['token'] ) : '';
$theme = isset( $attributes['theme'] ) ? sanitize_text_field( $attributes['theme'] ) : '';
$width = isset( $attributes['width'] ) ? sanitize_text_field( $attributes['width'] ) : '100%';
$success = isset( $attributes['successMessage'] ) ? sanitize_text_field( $attributes['successMessage'] ) : $content;
// Build shortcode attributes string
$shortcode_atts = ' token="' . $token . '"';
if ( $theme ) $shortcode_atts .= ' theme="' . $theme . '"';
if ( $width && $width !== '100%' ) $shortcode_atts .= ' width="' . $width . '"';
if ( $success ) $shortcode_atts .= ' success="' . $success . '"';
return do_shortcode( '[agentforms' . $shortcode_atts . ']' );
}