composer require tweekersnut/forms-lib
Add to your config/app.php providers:
'providers' => [
// ...
Tweekersnut\FormsLib\Laravel\FormsLibServiceProvider::class,
],
'aliases' => [
// ...
'Forms' => Tweekersnut\FormsLib\Laravel\Facades\FormsFacade::class,
]
Publish configuration:
php artisan vendor:publish --tag=forms-lib-config
use Tweekersnut\FormsLib\Core\FormBuilder;
use Tweekersnut\FormsLib\Fields\TextField;
use Tweekersnut\FormsLib\Fields\EmailField;
use Tweekersnut\FormsLib\Fields\SubmitField;
$form = new FormBuilder('contact_form', 'bootstrap');
$form->method('POST')->action('/submit');
$form->field(
(new TextField('name'))
->label('Name')
->required()
->rule('min:2')
);
$form->field(
(new EmailField('email'))
->label('Email')
->required()
);
$form->field(new SubmitField('submit', 'Send'));
echo $form->render();
use Tweekersnut\FormsLib\Laravel\Facades\FormsFacade as Forms;
$form = Forms::create('contact_form', 'bootstrap');
$form->method('POST')->action('/submit');
// Add fields...
echo $form->render();
Or use the helper:
$form = form('contact_form');
TextField- Text input with optional type (text, email, password, number, etc.)EmailField- Email input with validationPasswordField- Password inputNumberField- Number inputPhoneField- Phone number inputURLField- URL inputDateField- Date inputTimeField- Time inputDateTimeField- DateTime inputTextAreaField- Textarea with configurable rows/colsSelectField- Dropdown selectCheckboxField- Checkbox groupRadioField- Radio button groupFileField- File uploadHiddenField- Hidden inputSubmitField- Submit buttonResetField- Reset buttonButtonField- Generic button
Built-in validators:
required- Field is requiredemail- Valid email formatnumeric- Numeric valuephone- Valid phone numberurl- Valid URLdate- Valid datedatetime- Valid datetimemin:n- Minimum lengthmax:n- Maximum lengthminvalue:n- Minimum numeric valuemaxvalue:n- Maximum numeric valuematch:value- Match specific value
$validator = new Validator();
$validator->registerRule('custom_rule', function($value, $param, $field) {
return strlen($value) > 5;
});
use Tweekersnut\FormsLib\AJAX\AjaxHandler;
if (AjaxHandler::isAjaxRequest()) {
$handler = new AjaxHandler($form);
if ($handler->validate()) {
$handler->setSuccess(true)
->setMessage('Form submitted successfully')
->setData(['id' => 123]);
}
$handler->send();
}
<script src="form-handler.js"></script>
<script>
const formHandler = new FormHandler('#myForm', {
submitUrl: '/submit',
onSuccess: function(response) {
console.log('Success:', response);
},
onError: function(response) {
console.log('Error:', response);
}
});
</script>
Protect your forms from Cross-Site Request Forgery attacks:
use Tweekersnut\FormsLib\Security\CsrfToken;
session_start();
// Initialize CSRF token
$csrf = new CsrfToken('_token');
$token = $csrf->getToken();
// Add token to form
$form->withCsrfToken($token);
// Verify token on submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!$csrf->verifyRequest()) {
die('Invalid CSRF token');
}
// Process form...
}
$csrf = new CsrfToken($tokenName);
$csrf->generate() // Generate new token
$csrf->getToken() // Get current token
$csrf->getTokenName() // Get token field name
$csrf->verify($token) // Verify specific token
$csrf->verifyRequest() // Verify token from POST/GET
$csrf->regenerate() // Regenerate token (after login)
$csrf->clear() // Clear token
$csrf->setTokenLength($len) // Set token length
$form = new FormBuilder('myform', 'bootstrap');
$form = new FormBuilder('myform', 'tailwind');
See the examples/ directory for complete working examples:
01-basic-form.php- Basic form creation02-form-with-validation.php- Form validation03-ajax-form.php- AJAX form submission04-csrf-token-form.php- CSRF token protection
$form = new FormBuilder($name, $theme);
$form->method($method) // Set HTTP method
$form->action($url) // Set form action
$form->attributes($attrs) // Add HTML attributes
$form->field($field) // Add field
$form->values($data) // Set field values
$form->errors($errors) // Set validation errors
$form->validate($data) // Validate data
$form->render() // Render complete form
$form->renderField($name) // Render single field
$form->toArray() // Convert to array
$form->toJson() // Convert to JSON
$field->label($text) // Set label
$field->value($value) // Set value
$field->placeholder($text) // Set placeholder
$field->help($text) // Set help text
$field->required($bool) // Mark as required
$field->rule($rule) // Add validation rule
$field->rules($array) // Add multiple rules
$field->attributes($attrs) // Add HTML attributes
$field->addClass($class) // Add CSS class
$field->id($id) // Set element ID
Create reusable forms that can be embedded in forum posts and CMS content using simple shortcode syntax:
use Tweekersnut\FormsLib\Shortcodes\FormShortcode;
// Create and configure form
$form = new FormBuilder('contact_form', 'bootstrap');
$form->field((new TextField('name'))->label('Name')->required());
$form->field((new EmailField('email'))->label('Email')->required());
// Create shortcode
$shortcode = new FormShortcode($form);
// Add success callback
$shortcode->onSuccess(function ($data, $shortcode) {
// Save to database, send email, etc.
return ['success' => true];
});
// Register shortcode
$shortcode->registerShortcode('contact_form');
Use in content:
[contact_form]
[contact_form wrapper="custom-class"]
See SHORTCODES_GUIDE.md for complete documentation and examples.
- QUICKSTART.md - 5-minute quick start guide
- INTEGRATION_GUIDE.md - Detailed integration instructions for Core PHP and Laravel
- API_REFERENCE.md - Complete API reference
- SHORTCODES_GUIDE.md - Shortcode system documentation
- examples/ - Working examples for all features