Baigudin Software avatar
Baigudin Software logo
home
ru region
en region

PHP DOM Builder API 2.0

Baigudin Software is unveiled in global edition

Baigudin Software project has been unveiled in English global edition and it always accessed by www.baigudin.software/en/.

Work with fields of web form

We know that only created web form with its fields is actually nothing. We need to work with these fields of form. Well, when we are processing fields on a client side, but this  is friendly only for users. Eventually, they will send form data to a server, and we should be to analyze those data on a server side. In this instant, we need to process that, because we do not trust a user browser, and its form data, do we?

In this article, we will talk about classes, its settings and about basic principles for operating fields of web forms. The best way to talk about it that is a live example which is a form for sending your opinion to us if you set "Send to developers" checkbox. Here is this form:

Your opinion

How did you find us?:

* Name:

E-mail:

Upload:

Comment:

Send to developers:

* - Field must be filled

For abidance of our site style, the form has been processed by CSS styles with saving example HTML markup.

Let's create a new project for best understanding. We might have two files in the root directory of our server which names are index.php and Form.php. Also, we need a DomBuilder folder with the library.

Here is source code of index.php file:

<?php
// Add http header
header('Content-type: text/html; charset=utf-8');
// Include external files
require_once('DomBuilder/Elements.php');
require_once(
'Form.php');
// Import namespace 
use DomBuilder\Element as Element;
// Document type
Element::docType(Element::DOC_XHTML_10);
// Document compress flag
Element::docCompress(false);
// Document language 
Element::docLanguage('en');
// Print error flag
Element::printError(true);
// Create document
$document Element::create();
$document->insert('html')->insert('head')->after('body');
// Compiler has to say: "no warnings, no errors" :)
$document->find('head')
  ->
insert('title')->html('PHP DOM Builder form test')
  ->
after('meta')
  ->
attr('http-equiv''Content-Type')
  ->
attr('content''text/html; charset=utf-8');
// Add form
$document->find('body')->insertForm::get() );
// Output document
echo Element::getDocument($document);
?>

Perhaps, we do not have any special code in it. We are only including necessary files for working and creating a document.

Source code of Form.php file:

<?php
/**
 * HTML form example.
 * 
 * @author    Sergey Baigudin, baigudin@mail.ru
 * @copyright 2014-2016 Sergey Baigudin
 * @license   http://baigudin.software/license/
 * @link      http://baigudin.software
 */ 

use DomBuilder\Element as Element;
class 
Form
{
  
/** 
   * Returns generated form.
   * 
   * @return Element web form elements tree.
   */  
  
static public function get()
  {
    
$form self::_form();
    if( 
self::_isChecked($form) ) self::_save($form);
    return 
$form
  }
  
/** 
   * Creates a form.
   * 
   * @return Element web form elements tree.
   */  
  
static private function _form()
  {
    
// Create form
    
$form Element::create('form')->action('')->method('post')
      ->
enctype('multipart/form-data');
    
// Create message
    
$form->insert('p')->addClass('message')->html('Your opinion');
    
// Create SELECT
    
$form->insert('p')->insert('ext/str')->html('How did you find us?: ')
      ->
after('select')
        ->
insert('option')->value(0)
        ->
after('option')->value(1)->html('Search engine')
        ->
after('option')->value(2)->html('Social network')
        ->
after('option')->value(3)->html('Forum')
        ->
after('option')->value(4)->html('It was an accidental')
        ->
after('option')->value(5)->html('Other');
    
// Create INPUT type=text for name
    
$form->insert('p')->insert('ext/str')->html('* Name: ')
      ->
after('input/text')
      ->
fill(true)
      ->
maxlength(30);
    
// Create INPUT type=text for E-main
    
$form->insert('p')->insert('ext/str')->html('E-mail: ')
      ->
after('input/text')
      ->
reg('^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$')
      ->
maxlength(30);      
    
// Create INPUT type=file
    
$form->insert('p')->insert('ext/str')->html('Upload: ')
      ->
after('input/file')
      ->
fileSize(1024102400); 
    
// Create TEXTAREA          
    
$form->insert('p')->insert('ext/str')->html('Comment: ')
      ->
after('textarea');    
    
// Create INPUT type=checkbox
    
$form->insert('p')->insert('ext/str')->html('Send to developers: ')
      ->
after('input/checkbox');      
    
// Create INPUT type=submit
    
$form->insert('input/submit')->value('Send');
    
// Create note
    
$form->insert('p')->addClass('fill')
      ->
html('* - Field must be filled');      
    return 
$form;
  }  
  
/** 
   * Tests if form fields are gotten correctly
   * 
   * @param Element $form web form.
   * @return bool result of testing.
   */  
  
static private function _isChecked($form)
  {
    
// Chech that form data is gotten
    
if($form->find('input[type=submit]')->value() === false
      return 
false;
    
// Find all field and except the button
    
$list $form->find('input, select, textarea')
      ->
not('input[type=submit]');
    
$error false;
    
// Tests fields for errors
    
for($i=0$i<$list->length(); $i++) 
    {
      
$node $list->get($i);
      
$error |= $node->check()->error();  
      if( 
$node->error() == true self::_message($node);
    }
    return !
$error;
  }
  
/** 
   * Prints an error message.
   * 
   * @param Element $node web form input node.   
   */  
  
static private function _message($node)
  {
    
$nodeName $node->prev()->html();
    
$errorStr $node->errorStr();
    
// Find P element with class=message and add error string
    
$node->parents('form')->find('p.message')
      ->
insert('span')->addClass('error')->html("Error $nodeName $errorStr")
      ->
after('br');
  }
  
/** 
   * Saves gotten result.
   * 
   * @param Element $form web form.  
   */  
  
static private function _save($form)
  {
    
$span $form->find('p.message')
      ->
insert('span')->addClass('complete')
      ->
after('br')
      ->
prev();
    
// If checkbox is not set, when print the message
    
if($form->find('input[type=checkbox]')->get(0)->value() === false
    {
      
$span->html('Your opinion is successfully filled, but does not sent to us');
      return;
    }
    
$span->html('Thank you for your opinion!');
    
// ...
    // We save your opinion here
    // ...
  
}  
}

?>

The Form.php file like any object-oriented coding of most popular realizations has been based on a namespace autoloading and contains only one class realization which is Form class. Just, this class is described in global namespace and does not depend on an autoloader. All those  methods are static, and we need not more for this moment. The class has a single public Form::get method. This method returns an object of Element interface which contains an elements tree of the form.

The get method does not do something special. It calls a method for creating basic form (Form::_form), checks form fields for correcting by calling a Form::_isChecked method, and saves fields data if those are correct. After it returns generated form.

We need to customize all fields of the form for correctly checking. This procedure is implemented in Form::_form method. Like HTML, we have three classes, which are Element\Input, Element\Textarea, and Element\Select, for working with some fields. The Element\Input class is a base class for child classes which are corresponding to types of fields. For example, the Element\Input\Text class is a class for text type of input field. Every class implements a set of methods for its unique setting, for working with result, and automatically generating an attributes of this field which depend on received data of query.

Thus, when we create the class, we need not bother about an initialization. The class automatically gets field data for query. More about these class settings you can get from the documentation, and we want to mark more important methods here:

  • fill sets a flag of required filling field. By default it is set to false.
  • reg sets a regular expression for checking inputted user data.
  • maxlength sets a characters maximum count of filed. If value is not set, check is skipped.
  • fileSize sets an available size rage of receiving file.

Every class for working with form fields has value method which returns a field value of query. If value is not sent, method returns false. Thus, we check a fact of form sending by calling the Form::_isChecked method.

The check method tests a field for errors. The result of checking will be returned by error method. If error is occurred, we can get an error string by calling the errorStr method. So, we have done it for generating error messages.

If all fields are correctly filled, we save those data by Form::_save method calling.

Thus, we have considered an example for operating with the web form. This example is not optimized, but we wanted to give you an understanding about a concept. Optimization will be presented in the next articles.

To the previous article

To the articles list

To the next article