cache = new CacheManager('form_blocks', HOUR_IN_SECONDS);
// Initialize forms from filter
$this->forms = $this->registerForms();
$this->form_contact = apply_filters('jvb_form_contact', '');
// Hook into the CustomBlocks render system
add_filter('jvb_render_block_jvb_forms', [$this, 'render'], 10, 2);
// Register forms data for the block editor
add_action('enqueue_block_editor_assets', [$this, 'localizeFormsData']);
add_action('init', [$this, 'registerBlock']);
}
public function registerBlock()
{
register_block_type($this->path, [
'render_callback' => [$this, 'render']
]);
}
/**
* Register available forms
*/
protected function registerForms(): array
{
// Default forms can be registered here
$default_forms = [];
// Allow other plugins to register forms
$forms = apply_filters('jvb_register_forms', $default_forms);
// Process forms to ensure they have proper structure
$processed_forms = [];
foreach ($forms as $form_key => $form_config) {
$processed_forms[$form_key] = $this->processFormConfig($form_config);
}
return $processed_forms;
}
/**
* Process form configuration to ensure proper structure
*/
protected function processFormConfig(array $config): array
{
$defaults = [
'title' => 'Form',
'description' => [],
'submit' => 'Submit',
'success_title' => 'Thank You!',
'success_message' => ['Your message has been sent successfully.'],
'email_to' => get_option('admin_email'),
'email_subject' => 'New Form Submission',
'fields' => [],
'sections' => []
];
$config = array_merge($defaults, $config);
return $config;
}
/**
* Render the form block
*/
public function render(array $block, string $content): string
{
$form_type = $block['formType'];
if (empty($form_type) || !isset($this->forms[$form_type])) {
return '
No valid form type selected. Please edit this block and select a form type.
';
}
$cache_key = $this->cache->generateKey($block);
$cached = $this->cache->get($cache_key);
if ($cached) {
return $cached;
}
$rendered = $this->renderForm($form_type, $block);
$this->cache->set($cache_key, $rendered);
return $rendered;
}
/**
* Render the complete form
*/
protected function renderForm(string $type, array $attributes): string
{
$form_config = $this->forms[$type];
$custom_email_to = $attributes['customEmailTo'] ?? '';
$show_labels = $attributes['showLabels'] ?? true;
// Override email recipient if specified
if (!empty($custom_email_to)) {
$form_config['email_to'] = $custom_email_to;
}
// Allow filtering of email recipient
$form_config['email_to'] = apply_filters('jvb_form_email_to', $form_config['email_to'], $type, $attributes);
$submitted = get_query_var('jvb_submitted', false);
$error = get_query_var('jvb_form_error', false);
ob_start();
// Handle success state
if ($submitted) {
return $this->renderSuccessMessage($type, $submitted);
}
// Handle error state
if ($error) {
echo $this->renderErrorMessage($error);
}
// Generate unique form ID
$form_id = uniqid($type . '_');
// Render form
echo '';
$this->renderFormStart($type, $form_id, $attributes);
$this->renderFormFields($type, $show_labels);
$this->renderTurnstile();
$this->renderFormEnd($type, $form_id);
echo '
';
return ob_get_clean();
}
/**
* Render success message
*/
protected function renderSuccessMessage(string $type, string $submission_id): string
{
$form_config = $this->forms[$type];
$submission_data = $this->cache->get('submission_' . $submission_id);
ob_start();
echo '';
return ob_get_clean();
}
/**
* Render error message
*/
protected function renderErrorMessage(string $error): string
{
$message = urldecode($error);
$output = '';
return $output;
}
/**
* Get field label for display
*/
protected function getFieldLabel(string $form_type, string $field_name): string
{
$form_config = $this->forms[$form_type];
if (isset($form_config['fields'][$field_name]['label'])) {
return $form_config['fields'][$field_name]['label'];
}
return ucfirst(str_replace('_', ' ', $field_name));
}
/**
* Render form start tag
*/
protected function renderFormStart(string $type, string $form_id, array $attributes): void
{
$form_config = $this->forms[$type];
// Add form title and description
if (!empty($form_config['title'])) {
echo '' . esc_html($form_config['title']) . '
';
}
if (!empty($form_config['description'])) {
foreach ((array) $form_config['description'] as $desc) {
echo '' . wp_kses_post($desc) . '
';
}
}
echo '';
echo '
';
}
/**
* Localize forms data for block editor
*/
public function localizeFormsData(): void
{
$form_types = [
[
'label' => __('Select a form type', 'jvb'),
'value' => ''
]
];
foreach ($this->forms as $form_key => $form_config) {
$form_types[] = [
'label' => $form_config['title'] ?? ucwords(str_replace('-', ' ', $form_key)),
'value' => $form_key
];
}
error_log('Form Localization: '.print_r([
'formTypes' => $form_types,
'availableForms' => $this->forms,
'nonce' => wp_create_nonce('jvbForm')
], true));
wp_localize_script('jvb-forms-editor-script', 'jvbFormsData', [
'formTypes' => $form_types,
'availableForms' => $this->forms,
'nonce' => wp_create_nonce('jvbForm')
]);
}
/**
* Get registered forms
*/
public static function getForms(): array
{
return self::getInstance()->forms??[];
}
/**
* Get specific form configuration
*/
public static function getForm($type):array|null
{
return self::getInstance()->forms[$type] ?? null;
}
}