Baigudin Software avatar
Baigudin Software logo
home
ru region
en region

PHP DOM Builder API

We have participated in OS DAY 2017 conference

The Baigudin Software Company has participated in OS DAY – a fourth scientific-practical conference, which aims to determine a mission of Russia in developing sphere of operating systems.

Multi-language mode

We already told that the library supported a multi-language mode. We were talking about optimizations of application source code and also about the example of a user web form in previous articles.

Let's try to take these facts into consideration and improve the web form. We will add a multi-language support which will depend on given mode value. For this example, we chose two languages which are English and Russian.

So, let's consider a source code of the example before a debating. Here is it:

<?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()
  {
    
self::_listInit();
    
$form self::_form();
    if( 
self::_isChecked() ) self::_save($form);
    return 
$form
  }
  
/** 
   * Initializes input elements list
   */  
  
static private function _listInit()
  {
    
self::$_list Element::newList();
    
// Add 'How did you find us' field
    
$node Element::create('select')->key('select')
      ->
data('Как нас нашли?: ','ru')
      ->
data('How did you find us?: ','en');
    
$node->insert('option')->value(0);
    
$node->insert('option')->value(1)
      ->
html('В поисковике','ru')
      ->
html('Search engine','en');
    
$node->insert('option')->value(2)
      ->
html('В соцсети','ru')
      ->
html('Social network','en');
    
$node->insert('option')->value(3)
      ->
html('На форуме','ru')
      ->
html('Forum','en');
    
$node->insert('option')->value(4)
      ->
html('Шёл, шёл и нашел','ru')
      ->
html('It was an accidental','en');
    
$node->insert('option')->value(5)
      ->
html('Другое','ru')
      ->
html('Other','en');
    
self::$_list->push($node);
    
// Add 'Name' field
    
$node Element::create('input/text')->fill(true)->maxlength(30)->key('name')
      ->
data('* Имя: ','ru')
      ->
data('* Name: ','en');
    
self::$_list->push($node);
    
// Add 'E-mail' field
    
$node Element::create('input/text')->maxlength(30)->key('email')
      ->
reg('^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$')
      ->
data('E-mail: ');
    
self::$_list->push($node);    
    
// Add 'Upload' field
    
$node Element::create('input/file')->fileSize(1024102400)->key('file')
      ->
data('Файл: ','ru')
      ->
data('Upload: ','en');
    
self::$_list->push($node);     
    
// Add 'Comment' field
    
$node Element::create('textarea')->key('comment')
      ->
data('Комментарий: ','ru')
      ->
data('Comment: ','en');
    
self::$_list->push($node);    
    
// Add 'Send to developers' field
    
$node Element::create('input/checkbox')->key('send')
      ->
data('Передать разработчикам: ','ru')
      ->
data('Send to developers: ','en');
    
self::$_list->push($node);        
    
// Add 'Send' button
    
$node Element::create('input/submit')->key('submit')
      ->
value('Отправить','ru')
      ->
value('Send','en');
    
self::$_list->push($node);    
  }
  
/** 
   * Creates a form.
   * 
   * @return Element web form elements tree.
   */   
  
static private function _form()
  {
    
// Get submit button
    
$submit self::$_list->get('submit');
    
// Create form
    
$form Element::create('form')->action('')->method('post')
      ->
enctype('multipart/form-data');
    
// Create message
    
$form->insert('p')->addClass('message')
      ->
html('Ваш отзыв','ru')
      ->
html('Your opinion','en');
    
// Add all fields without the button
    
$list self::$_list->not($submit);
    
$length $list->length();
    for(
$i=0$i<$length$i++)
    {
      
$node $list->get($i);
      
$form->insert('p')->insert('ext/str')->html($node->data())->after($node);
    }
    
// Add Send button
    
$form->insert($submit);
    
// Create note
    
$form->insert('p')->addClass('fill')
      ->
html('* - Поле, обязательное для заполнения','ru')
      ->
html('* - Field must be filled','en');     
    return 
$form;
  }
  
/** 
   * Tests if form fields are gotten correctly
   * 
   * @return bool result of testing.
   */   
  
static private function _isChecked()
  {
    
// Get submit button
    
$submit self::$_list->get('submit');
    if(
$submit === false) return false;
    
// Chech that form data is gotten
    
if($submit->value() === false) return false;
    
// Find all field and except the button
    
$list self::$_list->not($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("Поле $nodeName $errorStr",'ru')
      ->
html("Error $nodeName $errorStr",'en')
      ->
after('br');
  }  
  
/** 
   * Saves gotten result.
   * 
   * @param Element $form web form.  
   */ 
  
static private function _save($form)
  {
    
$text '';
    
// Get checkbox value
    
$value self::$_list->get('send')->value();
    if(
$value === false
    {
      
$text = array(
        
'ru'=>'Отзыв заполнен, но нам не отправлен',
        
'en'=>'Your opinion is successfully filled, but does not sent to us'
      
);
    }
    else
    {
      
$text = array(
        
'ru'=>'Спасибо за Ваш отзыв!',
        
'en'=>'Thank you for your opinion!'
      
);      
    }
    
$form->find('p.message')->insert('span')->addClass('complete')->html($text);    
    
// Return from method if checkbox is not set
    
if($value === false) return;
    
// ...
    // We save your opinion here
    // ...
  

  
/**
   * Elements list
   * @var ElementList 
   */  
  
static private $_list;  
}

?>

We have two created files which are index.php and Form.php like the previous example about web form. The source code of index.php file you can recall in "Work with fields of web form" article, and the code of Form.php is presented above.

We also have the get method, but it has some different realization. Now, we define a $_list variable which is an object of ElementList class. This list is initialized by the _listInit method and contains initialized input fields of the web form. The data method gets any types  of variable as an argument. In our case, we give it a name of initializing fields while initializing time. Otherwise, the implementation of our class does not change. The get method calls a procedure for getting a tree of the web form elements, checks each element for errors, and saves the result if fields are initialized, and errors are not occurred. At the last, it returns the web form.

You might have seen some methods of our library, such as html, data, and etc, which get the second optional argument which  is a string key. This key is associated with giving text string as an output language. If the library determines a matching the key to the document language mode for each element while it is outputting a document; it outputs an associated text string for this key, else it outputs the last given text string. Thus, when we change the document language mode in index.php file, we change a language for the web form and for whole HTML document.

We told that the language mode was used for generating error strings. All implementations of input fields have defined error messages which depend on set language mode. Therefore, you get rich and flexible realization for working with form fields and are obviated to analyze and describe any occurred field errors.

So, we have optimized our web form and introduced its user interface which is maintaining two languages. The task is completed.

To the previous article

To the articles list