trendwerk/acf-forms

Helper to use ACF forms in the front-end.

0.2.0 2021-01-22 14:57 UTC

This package is auto-updated.

Last update: 2024-12-22 23:46:48 UTC


README

Active development for this package has been discontinued.

Helper package to use ACF forms in the front-end. What it does:

  • Adds the ability to send notifications
  • A default "Admin" notification
  • Saves entries to the database
  • Adds a wrapper around acf_form that does the repetitive work

This package requires Advanced Custom Fields Pro v5 to be installed.

Quick links: Install | Usage | Options | Example

Install

composer require trendwerk/acf-forms

Usage

Creating and showing a form with this package consists of four parts:

  1. Initialize package
  2. Create field group
  3. Register form
  4. Render form

Initialize

$acfForms = new \Trendwerk\AcfForms\AcfForms();
$acfForms->init();

This code should be run when bootstrapping your theme (traditionally done via functions.php). Initialization creates the entries post type and sets up defaults form handlers and notifications.

Create field group

Create a new field group in Advanced Custom Fields. When choosing a location where to show this field group, make sure you use Forms > Front-end is equal to Yes.

Register form

$acfForms->register($name, $options);

Render

Rendering a form consists of two parts:

  • Displaying the form
  • Handling form data and enqueue-ing scripts (Form::head())

For example:

use Trendwerk\AcfForms\Form\Form;

Form::head();
...
$form = new Form($name);
$form->render();

In reality, the render method will be called somewhere inside your actual template.

Options

Notifications

Notifications can be created by extending the Notification abstract class or the default Admin notification class.

Example

The example below walks through all three steps of creating and showing a form, based on a field group. This example uses Twig, Timber and Sphynx.

functions.php

$acfForms = new \Trendwerk\AcfForms\AcfForms();
$acfForms->init();

$acfForms->register('contact', [
    'acfForm'          => [
        'field_groups' => ['group_565474dcb9dd0'],
    ],
    'label'            => 'Contact',
]);

Field group keys can be found when showing the slug of the field group or in the corresponding JSON file.

page-contact.php

<?php
// Template name: Contact

use Timber\Post;
use Trendwerk\AcfForms\Form\Form;

Form::head();

$context = Timber::get_context();
$context['post'] = new Post();
$context['form'] = new Form('contact');

Timber::render('page-contact.twig', $context);

page-contact.twig

{% extends 'base.twig' %}

{% block content %}
  <h1>
    {{ post.title }}
  </h1>

  {{ post.content }}

  {{ form.render() }}
{% endblock %}