This repository has been archived on 2025-01-19. You can view files and clone it, but cannot push or open issues or pull requests.
oliverdavies.uk-old-sculpin/source/_posts/entityform.md

53 lines
2.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: Programmatically Load an Entityform in Drupal 7
date: '2015-12-22'
tags:
- drupal
- drupal-7
- drupal-planet
- entityform
meta:
description: How to programmatically load, render and embed an entityform in Drupal 7.
use: [posts]
---
{% block excerpt %}
I recently had my first experience using the [Entityform module](https://www.drupal.org/project/entityform) in a project. It was quite easy to configure with different form types, but then I needed to embed the form into an overlay. I was expecting to use the `drupal_get_form()` function and render it, but this didnt work.
Here are the steps that I took to be able to load, render and embed the form.
{% endblock %}
{% block content %}
## Loading the Form
The first thing that I needed to do to render the form was to load an empty instance of the entityform using `entityform_empty_load()`. In this example, `newsletter` is the name of my form type.
```language-php
$form = entityform_empty_load('newsletter');
```
This returns an instance of a relevant `Entityform` object.
## Rendering the Form
The next step was to be able to render the form. I did this using the `entity_form_wrapper()` function.
As this function is within the `entityform.admin.inc` file and not autoloaded by Drupal, I needed to include it using `module_load_include()` so that the function was available.
```language-php
module_load_include('inc', 'entityform', 'entityform.admin');
$output = entityform_form_wrapper($form, 'submit', 'embedded'),
```
The first argument is the `Entityform` object that was created in the previous step (Ive [submitted a patch](https://www.drupal.org/node/2639584) to type hint this within entityform so that its clearer what is expected), which is required.
The other two arguments are optional. The second argument is the mode (`submit` is the default value), and the last is the form context. `page` is the default value, for use on the submit page, however I changed this to `embedded`.
I could then pass this result into my theme function to render it successfully within the relevant template file.
## Resources
* [The entityform module](https://www.drupal.org/project/entityform)
* [My issue and patch to add the type hint to the entityform_form_wrapper function](https://www.drupal.org/node/2639584)
{% endblock %}