wjd/wjd-json-form-builder

Loads external JSON to render forms

v1.0.11 2024-09-17 12:41 UTC

This package is auto-updated.

Last update: 2024-09-17 10:59:12 UTC


README

Introduction

The wjd-json-form-builder is a PHP library designed to generate HTML forms based on JSON schemas. It provides functionality to create form markup dynamically by either fetching JSON data from an API endpoint or by processing a provided JSON string.

Latest Stable Version License

Installation

You can install the library via Composer:

composer require wjd/wjd-json-form-builder

Usage

Functions

Both functions return markup based on the provided JSON schema. The getFromApi function uses the getFromSchema function internally to process the data. Endpoints currently must always be publicly accessible.

getFromApi

getFromApi(string $getApiEndpoint)

Fetches a URL that returns a valid JSON format. The JSON structure is explained below.

getFromSchema

getFromSchema(string $json)

Accepts a JSON string and generates the corresponding form markup.

JSON Schema

{
    "$id": "http://mac-gyver.de/json/form.json",
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "Form",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string",
            "minLength": 1,
            "description": "First Name",
            "default": "Max"
        },
        "email": {
            "type": "string",
            "minLength": 1,
            "format": "email",
            "description": "Email"
        },
        "website": {
            "type": "string",
            "minLength": 1,
            "format": "uri",
            "description": "Website"
        },
        "birthdate": {
            "type": "string",
            "minLength": 1,
            "format": "date",
            "description": "Birthdate"
        },
        "age": {
            "type": "integer",
            "description": "Age",
            "minimum": 18,
            "maximum": 120
        },
        "gdpr": {
            "type": "boolean",
            "description": "Agreed to GDPR"
        },
        "selection": {
            "type": "object",
            "description": "Selection",
            "default": "2",
            "properties": {
                "1": {
                    "type": "string",
                    "description": "Option 1"
                },
                "2": {
                    "type": "string",
                    "description": "Option 2"
                },
                "3": {
                    "type": "string",
                    "description": "Option 3"
                }
            }
        },
        "password": {
            "type": "string",
            "description": "Password",
            "pattern": "(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,}",
            "additionalProperties": {
                "hint": {
                    "type": "string",
                    "description": "The password must contain at least one uppercase letter, one lowercase letter, one number, and be at least 8 characters long."
                },
                "confirm": {
                    "type": "boolean",
                    "default": true
                },
                "show": {
                    "type": "boolean",
                    "default": true
                }
            }
        },
        "honeypot": {
            "type": "string",
            "description": "obvious_honeypot"
        },
        "hidden": {
            "type": "string",
            "default": "2"
        }
    },
    "additionalProperties": {
        "action": {
            "type": "string",
            "default": "http://wjdjson.localdev/receiver.php"
        }
    },
    "required": [
        "email",
        "age",
        "gdpr"
    ]
}

Example Implementation

Below is an example of how to use the wjd-json-form-builder in your project:

<?php

namespace WjdDesignStudio\Helpers;

defined('ABSPATH') or die();

use WjdJsonFormBuilder\Form\Creator;

class CreateGeneratorForm {
    public function createFromSchema($endpoint, $schema) {
        $creator = new Creator();
        $form = $creator->getFromApi($schema, [
            'action' => '/',
            'method' => 'POST',
            'submit' => 'Generate PDF'
        ]);

        ob_start(); ?>
        <div id="loader-<?= $form['id'] ?>" style="display:none;">
            <img src="<?= WJD_DESIGN_STUDIO_PLUGIN_URL ?>/img/generate.svg" />
        </div>
        <a id="generation-<?= $form['id'] ?>" style="display:none;"></a>
        <script>
            window.addEventListener('wjdJsonFormBuilderScriptsLoaded', () => {
                const form = document.querySelector('.form-' + '<?= $form['id'] ?>');
                const loader = document.getElementById("loader-<?= $form['id'] ?>");
                const generation = document.getElementById("generation-<?= $form['id'] ?>");

                generation.style.display = "none";
                loader.style.display = "none";

                form.addEventListener('submit', (e) => {
                    e.preventDefault();
                    let data = wjdJsonFormToJson('<?= $form['id'] ?>');
                    console.log(data);

                    generation.style.display = "none";
                    loader.style.display = "block";

                    fetch('<?= $endpoint ?>', {
                        headers: {
                            "Content-Type": "application/json"
                        },
                        body: JSON.stringify(data),
                        method: "POST"
                    })
                    .then(response => response.json())
                    .then(json => {
                        loader.style.display = "none";
                        generation.style.display = "block";
                        console.log(json);
                        generation.innerHTML = `The print file has been generated and can be downloaded <a href="${json.result}" target="_blank">here</a>.`;
                    })
                    .catch(error => console.log(error))
                });
            })
        </script>
        <?php 
        $extension = ob_get_clean();
        return $form['markup'].$extension;
    }
}

Contribute and Maintain

  • Testing: Always test your changes before pushing to the repository. If you are uncertain about your changes, create a feature branch.
  • Changelog: Update the CHANGELOG.md file following Semantic Versioning.
  • Tags: Create a tag for each published version to be published to Packagist for Composer usage.