PHP code example of simplon / form

1. Go to this page and download the library: Download simplon/form library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

simplon / form example snippets


//
// easiest setup
//

(new FormFields())->add(
	new FormField('email')
);

//
// another way with a filter
//

(new FormFields())->add(
	(new FormField('email'))->addFilter(new CaseLowerFilter()) // lower case field value
);

//
// fields can also have rules
// 

(new FormFields())->add(
	(new FormField('email')->addRule(new EmailRule()) // make sure that we get an email address
);

//
// we can also combine these things
// 

(new FormFields())->add(
	(new FormField('email')
		->addRule(new EmailRule())
		->addFilter(new CaseLowerFilter())
);

//
// our fields
//

$fields = (new FormFields())->add(
	(new FormField('email'))->addRule(new EmailRule())
);

//
// set our data
//

$fields->applyInitialData(
	['email' => '[email protected]']
);

//
// testing ...
//

$fields->get('email')->getInitialValue(); // [email protected]
$fields->get('email')->getValue(); // [email protected]

//
// these values change if we enter for instance
// "[email protected]" in our form and hit submit ...
//

$fields->get('email')->getInitialValue(); // [email protected]
$fields->get('email')->getValue(); // [email protected]

//
// request data
//

$requestData = [
	'name' => 'Johnny',
	'email' => '',
];

//
// define fields
//

$fields = new FormFields();

$fields->add(
	new FormField('name')
);

$fields->add(
	(new FormField('email'))->addRule(new EmailRule())
);

//
// validation
//

$validator = new FormValidator($requestData);

if($validator->hasBeenSubmitted()) // any request data?
{
    if($validator->validate()->isValid())
    {
	    // all validated field data as array
    	var_dump($fields->getAllData());
    }
    else
    {
	    // array of error messages
    	var_dump($validator->getErrorMessages());

		// OR ...
		
    	// array of error fields    	
    	var_dump($validator->getErrorFields());
    }
}

//
// define fields
//

$nameElement = (new InputTextElement($fields->get('name')))
	->setLabel('Email address')
	->setDescription('Required in order to send you a confirmation');

$emailElement = (new InputTextElement($fields->get('email')))
	->setLabel('Email address')
	->setDescription('Required in order to send you a confirmation');

//
// apply to a block w/ one row
//

$block = (new FormViewBlock('default')) // set block ID to default
    ->addRow(
	    (new FormViewRow())
	    	->autoColumns($nameElement)
	    	->autoColumns($emailElement)
    )
;

//
// set view
//

$formView = (new FormView())->addBlock($block);


/**
 * @var FormView $formView
 */
use Simplon\Form\View\FormView;



/**
 * @var FormView $formView
 */
use Simplon\Form\View\FormView;


$field = (new FormField('name'))->addRule(new RequiredRule()) // 

$options = (new OptionsMeta())
	->add('DE', 'Germany')
	->add('FR', 'France')
	->add('US', 'United States')
	;
	
$field = (new FormField('shipping-to'))
	->addMeta($options)
	->addRule(new RequiredRule())
	;

(new FormField('name'))->addRule(new RequiredRule())

(new FormField('website'))->addRule(new UrlRule())

//
// set protocol if missing
//

(new FormField('website'))->addRule(new UrlRule('http'))

//
// allow only urls which hold foo.com
//

(new FormField('website'))->addRule(
    (new UrlRule())->setAdditionalRegex('/foo.com/')
)

(new FormField('email'))->addRule(new EmailRule())

(new FormField('photos'))->addRule(new ExactLengthRule(5))

(new FormField('photos'))->addRule(new MaxLengthRule(5))

(new FormField('photos'))->addRule(new MinLengthRule(1))

$callback = function(FormField $field)
{
	$model = $this->db->read(['email' => $field->getValue()]);

	return $model === null;
};

(new FormField('email'))->addRule(new CallbackRule($callback, 'Email address exists already'))

(new FormField('email'))->addRule(new IfFilledRule([new EmailRule()])

$email = new FormField('email');

$depRule = new FieldDependencyRule($email, [new EmailRule()]);

(new FormField('newsletter'))->addRule(new IfFilledRule([$depRule]))

$options = (new OptionsMeta())
	->add('DE', 'Germany')
	->add('FR', 'France')
	->add('US', 'United States')
	;
	
$field = (new FormField('shipping-to'))
	->addMeta($options)
	->addRule(new RequiredRule())
	->addRule(new WithinOptionsRule())
	;

(new FormField('email'))->addFilter(new CaseLowFilter()); // [email protected] --> [email protected]

(new FormField('name'))->addFilter(new CaseTitleFilter()); // foo bar --> Foo Bar

(new FormField('name'))->addFilter(new CaseUpperFilter()); // foo bar --> FOO BAR

(new FormField('emai'))->addFilter(new TrimFilter()); // " [email protected] " --> "[email protected]"

(new FormField('emai'))->addFilter(new TrimFilter("$")); // "[email protected]$" --> "[email protected]"

(new FormField('emai'))->addFilter(
	(new TrimFilter())->addChars("$")
);

// " [email protected]$" --> "[email protected]"

(new FormField('emai'))->addFilter(new TrimLeftFilter()); // " [email protected]" --> "[email protected]"

(new FormField('emai'))->addFilter(new TrimRightFilter()); // "[email protected] " --> "[email protected]"

(new FormField('comment'))->addFilter(new XssFilter());

// "A comment <script>...</script>" --> "A comment"

//
// fields
//

$emailId = 'email';

$fields = (new FormFields())->add(
	(new FormField($emailId))->addRule(new EmailRule())
);

//
// validation
//

$validator = (new FormValidator($_POST))->addFields($fields)->validate();

if ($validator->hasBeenSubmitted())
{
	// do something when form is OK
}

//
// build view
//

$view = (new FormView())->addElement(
	(new InputTextElement($fields->get($emailId)))->setLabel('Email address')
);

//
// render view
// https://github.com/fightbulc/simplon_phtml
// 

echo (new Phtml())->render('page.phtml', ['formView' => $view]);
	
/**
 * @var FormView $formView
 */
use Simplon\Form\View\FormView;

	
/**
 * @var FormView $formView
 */
use Simplon\Form\View\FormView;


$block = new FormViewBlock('foo');

(new FormView())->addBlock($block);

$block = new FormViewBlock('foo');

$someElement = ... ; // some element

$block->addRow(
	(new FormViewRow())->autoColumns($someElement) // takes up all columns
);

(new FormView())->addBlock($block);

// before

// all auto columns

$block->addRow(
	(new FormViewRow())
		->autoColumns($someElement) // takes up half of all columns
		->autoColumns($someOtherElement) // takes up half of all columns
);

// after

// before

// two rows with mixed width specifications

$block
	->addRow(
		(new FormViewRow())
			->threeColumns($someElement) // takes up 3 columns
			->autoColumns($someOtherElement) // takes everything what is left (13 columns)
	)
	->addRow(
		(new FormViewRow())
			->tenColumns($someElement) // takes up 10 columns
			->sixColumns($someOtherElement) // takes up 6 columns
	)
;

// after

$element = new InputTextElement(
	new FormField('name')
);

$element
	->setLabel('Your name')
	->setPlaceholder('Enter your name ...')
	->setDescription('Name is needed so that we can address your properly')
	;
	
// attach to FormView ...

$element = new InputPasswordElement(
	new FormField('password')
);

$element
	->setLabel('Your password')
	->setPlaceholder('Enter your password ...')
	->setDescription('Needed so that you can login')
	;

// attach to FormView ...

$element = new InputHiddenElement(
	new FormField('counter')
);

// attach to FormView ...

$element = new TextareaElement(
	new FormField('comment')
);

$element
	->setLabel('Your comment')
	->setPlaceholder('Enter your comment ...')
	->setRows(10) // determines rows-height; default is 4
	;
	
// attach to FormView ...

$options = (new OptionsMeta())->add('yes', 'I herewith confirm ...');

$confirmElement = new CheckboxElement(
	(new FormField('confirm'))->addMeta($options)
);

// attach to FormView ...

// [ ] I herwith confirm ...

$options = (new OptionsMeta())
	->add('Magazines')
	->add('Books')
	->add('Newspapers')
	;

$confirmElement = new CheckboxElement(
	(new FormField('reading'))->addMeta($options)
);

// attach to FormView ...

// [ ] Magazines
// [ ] Books
// [ ] Newspapers

$options = (new OptionsMeta())
	->add('Magazines')
	->add('Books')
	->add('Newspapers')
	;

$confirmElement = new RadioElement(
	(new FormField('reading'))->addMeta($options)
);

// attach to FormView ...

// ( ) Magazines
// ( ) Books
// ( ) Newspapers

$element = new SubmitElement('Save data', ['foo-class', 'bar-class']); // values are optional
	
// attach to FormView ...

$options = (new OptionsMeta())
	->add('DE', 'Germany')
	->add('FR', 'France')
	->add('US', 'United States')
	->add('...')
	->add('...')
	->add('...')
	;

$element = new DropDownElement(
	(new FormField('countries'))->addMeta($options)
);

$element
	->setLabel('City')
	->setDescription('Search for a city')
	->enableMultiple()		// allows selection of multiple options
	->enableSearchable()	// lets user search over options
	->enableAdditions()		// lets user add new options
;

// attach to FormView ...

$element = new TimeListElement(
	new FormField('time')
);

$element
	->setInterval(30) 	// build time options with 30 minutes interval
	->enableNone() 		// add "none" option
	;

// attach to FormView	

// - None
// - 00:00
// - 00:30
// - 01:00
// - 01:30
// - ...
// - ...
// - ...

$element = new DateListElement(
	new FormField('date')
);

$element
	->setFormatOptionLabel('D, d.m.Y') 	// label for each option; e.g. Sat, 01.04.2017
	->setFormatOptionValue('Y-m-d') 	// value for each option; e.g. 2017-04-01
	->setStartingDate('2017-04-01') 	// set starting date; YYYY-MM-DD or unix time stamp
	->setDays(7) 						// build date options for n days from given start date
	->enableNone() 						// add "none" option
	;

// attach to FormView	

// - None
// - Sat, 01.04.2017
// - Sun, 02.04.2017
// - Mon, 03.04.2017
// - Tues, 04.04.2017
// - ...
// - ...
// - ...

$element = new DateCalendarElement(
	new FormField('date')
);

$calendar
	->setLabel('Date')
	->dateOnly() 					// only show dates
	->setDateFormat('DD/MM/YYYY') 	// format of the selected date; e.g. 01/04/2017

// attach to FormView	

//
// start date range
//

$startDateElement = (new DateCalendarElement(new FormField('startDate')))
	->setLabel('Start date')
	->dateOnly()
	->setDateFormat('DD/MM/YYYY')
	;

//
// end date range
//

$endDateElement = new DateCalendarElement(
	new FormField('endDate'),
	$startDateElement // pass in related DateCalendarElement instance
);

$endDateElement
	->setLabel('End date')
	->dateOnly()
	->setDateFormat('DD/MM/YYYY')
	;

$jsOptions = (new AlgoliaPlacesApiJs())
	->setType(AlgoliaPlacesApiJs::TYPE_CITY)
	;

$cityElement = new DropDownApiElement(new FormField('city'), $jsOptions);

$cityElement
	->enableMultiple()
	->setLabel('City')
	->setDescription('Search for a city')
	;

$imageElement = new ImageUploadElement(new FormField('urlImage'));

<div class="ui basic segment">
    <h3>Image</h3>
    <?= $formView->getBlock('image')->render() 

$requestData = $_POST;

//
// oned field block
//

$storedData = [
    'clones' => [
        'address' => [
            'address' => 'Mr.',
            'firstname' => 'Peter',
            'lastname' => 'Foo',
            'email' => '[email protected]',
        ]
    ]
];

//
// define core clone fields
//

$cloneBlock = (new CloneFields('address'))
    ->add((new FormField('address'))->addMeta((new OptionsMeta())->add('Mr.')->add('Mrs.'))->addRule(new RequiredRule()))
    ->add((new FormField('firstname'))->addRule(new RequiredRule()))
    ->add((new FormField('lastname'))->addRule(new RequiredRule()))
    ->add((new FormField('email'))->addRule(new EmailRule()))
;

//
// add clone fields to our form fields
// and apply stored data if available
//

$fields = (new FormFields())
    ->add($cloneBlock)
    ->applyBuildData($storedData, $requestData)
;

$validator = (new FormValidator($requestData))->addFields($fields)->validate();

if ($validator->hasBeenSubmitted())
{
    if ($validator->isValid())
    {
        var_dump($fields->getAllData());
        
        // expected result depending on how many blocks you cloned ...
        // results are wrapped in their clone field block ID

        // [        
        //     'clones' => [
        //          'address' => [
        //              [
        //                  'address' => 'Mr.',
        //                  'firstname' => 'Peter',
        //                  'lastname' => 'Foo',
        //                  'email' => '[email protected]',
        //              ],
        //              [
        //                  ...
        //              ]
        //          ]
        //     ]
        // ]

    }
}

//
// build view
// 

$build = function (FormViewBlock $viewBlock, string $token) use ($fields) {
    $addressElement = (new DropDownElement($fields->get('address', $token)))->enableMultiple()->setLabel('Address');
    $firstnameElement = (new InputTextElement($fields->get('firstname', $token)))->setLabel('First name');
    $lastnameElement = (new InputTextElement($fields->get('lastname', $token)))->setLabel('Last name');
    $emailElement = (new InputTextElement($fields->get('email', $token)))->setLabel('Email address')->setDescription('Required in order to send you a confirmation');

    return $viewBlock
        ->addRow((new FormViewRow())->autoColumns($addressElement))
        ->addRow((new FormViewRow())->autoColumns($firstnameElement)->autoColumns($lastnameElement))
        ->addRow((new FormViewRow())->autoColumns($emailElement))
        ;
};

$addressBlocks = (new CloneFormViewBlock($cloneBlock))->build($build);

$view = (new FormView())
    ->setComponentDir('../../assets/vendor')
    ->addBlocks($addressBlocks)
;

//
// render view
// https://github.com/fightbulc/simplon_phtml
//

echo (new Phtml())->render(__DIR__ . '/page.phtml', ['formView' => $view]);


/**
 * @var FormView $formView
 */
use Simplon\Form\View\FormView;


/**
 * @var FormView $formView
 */
use Simplon\Form\View\FormView;


//
// mark only optional fields
//

FormView::useOptionalLabel(true);

//
// mark only 

//
// override optional text
//

FormView::setOptionalLabel('opcional'); // translated to Spanish

//
// override