This tutorial is a work in progress. Please comment if something is not clear
Prerequisites
What will you learn?
- Create a form
- Validate a form
Tutorial
Creating the form
At first we need to create the form and its element.
// fetch spoon
require_once 'spoon/spoon.php';
// create form
$frm = new SpoonForm('myForm'); // uitleg over action, method
// add name (input field)
$frm->addText('name');
// add email (input field)
$frm->addText('email')
->setAttribute('type', 'email'); // html5 'email' type attribute
// add phone number (input field)
$frm->addText('phone')
->setAttribute('placeholder', 'digits only') // html5 placeholder attribute
->setAttribute('required'); // html5 'required' attribute
// add bio (textarea)
$frm->addTextarea('bio');
// add date of birth
$frm->addDate('date_of_birth', null, 'd/m/Y'); // @todo uitleg over mogelijke masks
$frm->addTime('time_of_birth');
// add gender
$gender = array();
$gender[] = array('label' => 'Male', 'value' => 'male');
$gender[] = array('label' => 'Female', 'value' => 'female');
$frm->addRadiobutton('gender', $gender, 'male');
// add subscribe to newsletter (single checkbox)
$frm->addCheckbox('subscribe', true);
// add programming languages (multi checkbox)
$languages = array();
$languages[] = array('label' => 'PHP', 'value' => 'php');
$languages[] = array('label' => 'Ruby', 'value' => 'ruby');
$languages[] = array('label' => 'C#', 'value' => 'c_sharp');
$frm->addMultiCheckbox('languages', $languages, 'php');
// add country (dropdown)
$frm->addDropdown('country', SpoonLocale::getCountries(), 'BE');
// add cartoon characters (multi select dropdown)
$cartoons['Smurfs']['papa'] = 'Papa smurf';
$cartoons['Smurfs']['smurfette'] = 'Smurfette';
$cartoons['Smurfs']['brainy'] = 'Brainy smurf';
$cartoons['Smurfs']['jokey'] = 'Jokey smurf';
$cartoons['Simpsons']['homer'] = 'Homer';
$cartoons['Simpsons']['marge'] = 'Marge';
$cartoons['Simpsons']['bart'] = 'Bart';
$cartoons['Simpsons']['lisa'] = 'Lisa';
$frm->addDropdown('toons', $cartoons, array('homer', 'bart'), true);
// add pdf (file)
$frm->addFile('pdf');
// add photo (image)
$frm->addImage('photo');
// add preferred password (password)
$frm->addPassword('password');
// add hidden value(s)
$frm->addHidden('preferences', 'random value');
// add submit button
$frm->addButton('submit', 'Submit');
The template
Now we're going to make the html template that will hold our form fields. You can either type all this manually or use a built-in method to provide you with the basics. I personally start by copy pasting the generated code from SpoonForm::getTemplateExample(). In this example I took that generated code and modified it to suit my needs.
The code below needs to go in your 'form.tpl' file.
{form:myForm}
{$hidPreferences}
<p>
<label for="name">Name*</label><br />
{$txtName} {$txtNameError}
</p>
<p>
<label for="email">Email*</label><br />
{$txtEmail} {$txtEmailError}
</p>
<p>
<label for="phone">Phone</label><br />
{$txtPhone} {$txtPhoneError}
</p>
<p>
<label for="bio">Bio*</label><br />
{$txtBio} {$txtBioError}
</p>
<p>
<label for="dateOfBirth">Date of birth*</label><br />
{$txtDateOfBirth} {$txtDateOfBirthError}
</p>
<p>
<label for="timeOfBirth">Time of birth*</label><br />
{$txtTimeOfBirth} {$txtTimeOfBirthError}
</p>
<p>
Gender*<br />
{iteration:gender}
<label for="{$gender.id}">{$gender.rbtGender} {$gender.label}</label>
{/iteration:gender}
{$rbtGenderError}
</p>
<p>
{$chkSubscribe} <label for="subscribe">Subscribe to our newsletter*</label>
{$chkSubscribeError}
</p>
<p>
Languages*<br />
{iteration:languages}
<label for="{$languages.id}">{$languages.chkLanguages} {$languages.label}</label>
{/iteration:languages}
{$chkLanguagesError}
</p>
<p>
<label for="country">Country*</label><br />
{$ddmCountry} {$ddmCountryError}
</p>
<p>
<label for="toons">Cartoon characters</label><br />
{$ddmToons} {$ddmToonsError}
</p>
<p>
<label for="pdf">Pdf*</label><br />
{$filePdf} {$filePdfError}
</p>
<p>
<label for="photo">Photo*</label><br />
{$filePhoto} {$filePhotoError}
</p>
<p>
<label for="password">Password</label><br />
{$txtPassword} {$txtPasswordError}
</p>
<p>{$btnSubmit}</p>
{/form:myForm}
Validating the form
Now that we have a form and a template, we're going to validate the form and make sure it's rendered using 'form.tpl'.
// form was submitted
if($frm->isSubmitted())
{
// name is required
$frm->getField('name')->isFilled('Please fill out your name');
// email is required
$frm->getField('email')->isEmail('Please provide a valid email address.');
// phone is NOT required
if($frm->getField('phone')->isFilled())
{
// now that we know it's filled, it needs to be numeric!
$frm->getField('phone')->isNumeric('Digits only please!');
}
// bio is required
if($frm->getField('bio')->isFilled('Please tell us more about yourself.'))
{
// has to be at least 10 characters
$frm->getField('bio')->isMinimumCharacters(10, 'Surely you can tell us more!');
}
// date is required (and needs to be valid)
$frm->getField('date_of_birth')->isValid('Please provide a valid date. (dd/mm/yyyy)');
// time needs to be valid
$frm->getField('time_of_birth')->isValid('When exactly were u born? (hh:mm)');
// gender is required
$frm->getField('gender')->isFilled('Tell us your gender please.');
// you HAVE to subscribe to our newsletter :)
$frm->getField('subscribe')->isFilled('Please subscribe to our newsletter!');
// you have to check at least 1 programming language
$frm->getField('languages')->isFilled('Please choose at least 1 language.');
// country is required
$frm->getField('country')->isFilled('Please select your country.');
/*
* Validate the pdf file. Following conditions need to be met:
* - pdf is required
* - file needs to have the 'pdf' extension
* - file needs to be smaller than 2MB
*/
if($frm->getField('pdf')->isFilled('Please upload a pdf.'))
{
// needs to be a pdf
if($frm->getField('pdf')->getExtension() != 'pdf')
{
$frm->getField('pdf')->addError('You have to upload a pdf document.');
}
// it seems to be a .pdf file
else
{
// may not be larger than 2MB
$frm->getField('pdf')->isFilesize(2, 'mb', 'smaller', 'Too large. 2MB max');
}
}
/*
* Validate the image. Following conditions apply:
* - image is required
* - image needs to be a jpeg or png
* - image needs to be smaller than 2MB
* - dimensions should exceed 640x480 pixels
*/
$image = $frm->getField('photo'); // just to shorten the code
if($image->isFilled('Please upload an image.'))
{
// image has the jpg/png extension
if($image->isAllowedExtension(array('jpg', 'png'), 'Only jpg/gif are allowed.'))
{
// image is not larger than 2MB
if($image->isFilesize(2, 'mb', 'smaller', 'Too large. 2MB maximum'))
{
// dimensions are minium 640x480
$image->hasMinimumDimensions(640, 480, 'Too small. 640x480 minimum');
}
}
}
// password is required
$frm->getField('password')->isFilled('Please choose a password');
/*
* The entire form was submitted correctly based on the iput validation
* we did above.
*/
if($frm->isCorrect())
{
// all the information that was submitted
$data = $frm->getValues();
// dump data for demo purpose
Spoon::dump($data);
}
}
/*
* Now all we need to do is create a template and parse this
* form into the template.
*/
$tpl = new SpoonTemplate();
$tpl->setForceCompile(true);
$tpl->setCompileDirectory('cache');
$frm->parse($tpl);
$tpl->display('form.tpl');
Final output
You can now view your form in your browser. Play with it to see how the error messages react and if everything is filled out correctly you should get output similar to the one below
array(15) {
["form"] => string(6) "myForm"
["name"] => string(14) "Davy Hellemans"
["email"] => string(22) "davy@spoon-library.com"
["phone"] => string(10) "1234567890"
["bio"] => string(93) "I don't really like clowns. They just assume they're funny"
["date_of_birth"] => string(10) "03/08/1983"
["time_of_birth"] => string(5) "13:37"
["gender"] => string(4) "male"
["subscribe"] => bool(true)
["languages"] => array(1) {
[0] => string(3) "php"
}
["country"] => string(2) "BE"
["toons"] => array(2) {
[0] => string(9) "smurfette"
[1] => string(5) "homer"
}
["password"] => string(4) "leet"
["preferences"] => string(12) "random value"
["submit"] => string(6) "Submit"
}
Conclusion
Based on the example you should now be able to create some basic (and advanced) forms.
Pieter Beulque wrote 2 years ago
SpoonFile?