Building custom front-end forms with WordPress page templates can be surprisingly tedious. The most frustrating part is often writing the HTML form by hand and validating the submitted data safely. That usually leads to a lot of repetitive code and more opportunities for mistakes.
The Nette Forms library, extracted from the Nette PHP framework, can help simplify that workflow. In this example, all of the code lives inside a standard WordPress page template.
Step 1: install and load Nette Forms
Install the package with Composer
composer require nette/forms
If you are new to Composer in WordPress, make sure the autoloader is already available in your theme or plugin.
Load the Nette Forms classes
After installation, include Composer’s autoloader and import the form class:
require_once dirname(__FILE__) . '/vendor/autoload.php';
use Nette\\Forms\\Form;
Create and display the form
This is the key step. Instead of writing a large amount of raw HTML, the form is defined in PHP. That reduces boilerplate and makes it easier to keep validation and rendering together.
$uid = wp_get_current_user()->ID;
$nickname = get_user_meta($uid, 'nickname', true);
$card = get_user_meta($uid, 'card', true);
$form = new Form;
$form->setMethod('POST');
$form->addText('nickname', 'Nickname:')
->setRequired('Please enter a nickname.')
->setDefaultValue($nickname);
$form->addText('card', 'Card Number:')
->setDefaultValue($card);
$form->addSubmit('send', 'Submit');
echo $form;
In the example above:
wp_get_current_user()is used to retrieve the current user.get_user_meta()is used to prefill the form with existing user meta values.
Submit to the back end
The final step is handling the submitted data. Before saving anything, let Nette Forms validate the form according to the rules you set. If validation succeeds, save the values back to WordPress. If validation fails, show the form errors.
if ($form->isSuccess()) {
$values = $form->getValues();
update_user_meta($uid, 'nickname', $values->nickname);
update_user_meta($uid, 'card', $values->card);
echo '<p>Saved successfully.</p>';
}
For a small example the difference may not look dramatic, but once a form becomes larger, using a form library like Nette Forms can save a lot of time and reduce the chance of validation or security mistakes.
