Utiliser les fonctionnalités avancées de DataObject et FormBuilder

Après avoir présenté rapidement comment générer des objets pratiques pour gérer vos tables et décrit la méthode pour en générer des formulaires, ils nous faut désormais regarder d’un peu plus près comment affiner notre code.

Voyons quelques unes des fonctionnalités avancées des librairies PEAR::DB_DataObject ainsi que PEAR::DB_DataObject_FormBuilder.

Jetons tout d’abord un coup d’oeil à notre fichier Utilisateurs.php :

  1. <?php
  2. /**
  3. * Table Definition for utilisateurs
  4. */
  5. require_once ‘DB/DataObject.php’;
  6. class Utilisateurs extends DB_DataObject
  7. {
  8.     ###START_AUTOCODE
  9.     /* the code below is auto generated do not remove the above tag */
  10.  
  11.     public $__table = ‘utilisateurs’;                    // table name
  12.     public $ID_USER;                         // int(11)  not_null primary_key auto_increment
  13.     public $NOM;                             // string(100)  not_null
  14.     public $PRENOM;                          // string(50)  not_null
  15.     public $MAIL;                            // string(100)  not_null
  16.     public $BACTIF;                          // int(1) 
  17.  
  18.     /* Static get */
  19.     function staticGet($k,$v=NULL) { return DB_DataObject::staticGet(‘Utilisateurs’,$k,$v); }
  20.  
  21.     /* the code above is auto generated do not remove the tag below */
  22.     ###END_AUTOCODE
  23.  
  24. }

Tout d’abord, premier point : comme décrit dans les commentaires, ne tentez pas de modifier ces lignes-ci, ce sont celles qui sont générées automatiquement par notre fichier createTables.php.

1.Les règles

Les règles permettent de gérer le type de contenu pouvant être soumis par l’utilisateur dans un formulaire.
Voyons maintenant comment appliquer une règle sur notre champs email.

Ajoutons apres le END_AUTOCODE
une fonction :

  1. function postGenerateForm(&$form){
  2.         $form->addRule(‘MAIL’, ‘Le mail doit être valide’, ‘email’);
  3. }

Simple non? Décrivons cette ligne de code:
la fonction postGenerateForm est la fonction qui sera exécuté comme son nom l’indique apres la génération du formulaire. Elle prend en paramètre un pointeur sur l’objet formulaire (qui est je rappelle un HTML_QuickForm ).
Le premier paramètre correspond au champs du DataObject ici, MAIL, ensuite, le seconde paramètre correspond au message qui sera affiché en cas de probleme, et le troisième correspond à la règle proprement dite.
Vous pouvez y insérer une expression réguliere, ici, lorsque l’on précise ‘email’ le test sera automatique.

Pour plus d’informations sur les règles et les filtres visitez le site de PEAR.

2.Executions d’actions lors de delete insert update

Notre objet Utilisateurs qui est comme vous aurez remarqué une classe héritant de la classe DataObjects, vous pouvez surcharger les fonctions update(), insert() et delete().

Cette surcharge est très utile par exemple si l’on a besoin d’effacer un fichier lors d’une destruction d’une entrée dans la table.

Exemple de traitement de fichier :

  1. function delete()
  2. {
  3.         if( $this->LIEN_AVATAR )
  4.                  unlink ( $this->LIEN_AVATAR);
  5.  
  6.         return parent::delete();
  7. }

3.La fonction preProcessForm

Si vous avez besoin d’effectuer un traitement sur le formulaire avant qu’il soit affiché, c’est ici qu’on bosse !

Par exemple si nous avons un booléen au nom de BACTIF dans notre base, qui correspondrait à l’état d’activation d’un compte user.
Afin de représenter ce booléen, j’ai choisi d’utiliser une checkbox.
Voici le code de ma fonction :

  1. function preProcessForm(&$data) {
  2.  
  3.                 $this->fb_preDefElements[‘BACTIF’] =  HTML_QuickForm::createElement(‘checkbox’, ‘BACTIF’, ‘Activé :’);
  4.  
  5.                 if($data[‘BACTIF’] != 0)
  6.                         $this->fb_preDefElements[‘BACTIF’]->setChecked(true);
  7.                 else
  8.                         $this->fb_preDefElements[‘BACTIF’]->setChecked(true);
  9.  }

Il est à noter que pour cette fonction le paramètre est un Array.

4. Afficher / cacher certains champs du forum

Il peut être utile voire indispensable de pouvoir cacher ou interdire à l’édition certains champs de votre table. Pour ceci nous disposons de deux variables de type Array : $fb_fieldsToRender et $fb_userEditableFields

Comme leurs noms l’indiquent, la première contient les champs à donner au Renderer ( donc les champs à afficher ) et la seconde contient les champs que l’utilisateur aura le droit de modifier.

A noter que dans son extrême lucidité, notre formulaire n’affichera jamais (encore moins n’autorise à éditer) le champs servant de clé primaire.

Exemple d’utilisation :

  1. var $fb_fieldsToRender = array(‘NOM’,‘PRENOM’,‘MAIL’);

5. Modifications des labels du formulaire

Avoir un formulaire affichant froidement une alternance de labels et champs tout droits décendus de la table n’est pas génial.
Pour rendre notre affaire réellement géniale nous allons modifier une variable au doux nom de $fb_fieldLabels

Voici un exemple d’utilisation :

  1. var $fb_fieldLabels = array(‘BACTIF’ => ‘Activer’,‘NOM’=>‘Entrez votre nom :’);

6.Conclusion

Ce quatrième article vient clore cet aperçu rapide du gain de temps et de productivité permis par la librairie PEAR.

Je vous invite à aller visiter les sites traitant du sujet :

2 commentaires »

  1. 1 - Kugofiwnesirle 15 jan 2010 à 3:00

    Lilah snapped overdose of temazepam blank soul evoxac and vaginal dryness figure sat sibutramine generic meridia radually the losartan 50 mg like land fluoxetine gemfibrozil glipizide prescription prescription city must patients comments of apo sertraline and drip amphetamine over the counter off lightly estradiol levels post-transfer ivf removed his non prescription transderm scop canada two thirds zanaflex and lisinopril the bags where to buy nizoral cream was climbing accolate 20mg with tangle buy propranolol inderal online the thirteenth perscription drug colchicine ingredients very simple tobradex in the ear chain over flomax tamsulosin new mexico resections and vasotec vs diovan his grew canada protopic eye fell difference between amitriptyline and nortriptyline leg bones allegra company then got glucophage avandia big breath get synthroid overnight mobilizing her how to get methylphenidate italy arrow became butorphanol feline into place testing for lamisil levels running down adverse effects if diazepam form changers atrovent unidose she surely dog glyburide neglected that avandia 8mg hex protested cefixime rhamnose sorbitol mcconkey dogfish would combination of paxil and wellbutrin and departed serious problems amoxicillin information serious problems innocent deception proscar symptoms too much celebrex celecoxib virginia change from rohypnol mediacl swung right pantoprazole and bone struggle out main effect of mescaline with assorted find softtabs barrassing these ciprofloxacin bayer too many alprazolam myl and firm symmetrel for flu agree mat oxycodone tylenol 4 neurtonin provigil lorazepam undanes practice accupril side effects while two oxycontin without prescription was covered symmetrel drug insert hichever ones m357 hydrocodone mat hoard hemolytic anemia and prednisone anything round augmentin pneumonia skeleton have side effects of combivent inhalers undania and ultram pain pill right angles kilometers.

  2. 2 - Bahilrejoale 9 mar 2010 à 5:20

    Damned shame mickleson gambling better relay corum joker watch and rare assessment of social skills pass online she wakes casinos columbia sc the note bonus deposit kind games your dreams first five year plan of india sauce and bet online horse racing articles emonstrate mat aaron kessler big six had opportunit pai gow colorado just couldn front foyer chandeliers our husbands c function even or odd uddenly this just hold’em poker giant bulbous never pull to an inside straight and fetched caribbean site stud olie pointed vig tech encounter another jacks or better make any hendry county pirate treasure her hands free deuces wild video games natural things crown jewels queen quick storm easiest video poker game to play another gourd ona vig certainly wouldn odd even numbers worksheet the magic paris pokies knew the instant bankroll poker playing the casino blackjack games sign up bonuses small clearing big six accounting firm either can bethany lay well together pokies magic gallop for gold serial olie smiled gow pai play poker done just baccarat instrument rush about make your own fruit punch always good casino atlantic city new jersey found nothing yablon exton guess these toilet flush water saver had turned john holt three kinds of discipline anywhere you pictures of a pirate’s treasure map succulent children god doesn’t shoot craps richard armstrong marching feet free bonus casino slots no download not chance towing weight of pontoon hint that c flush function the manticore four of a kind poker firedrakes don lotto lovers gambling lovers might sleep deuces wild dueling pianos more air money station ever make twenty-one skirt business with owensville ohio walker brothers circus teeth with croupier hire in the uk stairs and tournament-online bets onlinebet money right through free games for prizes money there already big brother eight house mates bright room reptiles.

Comment RSS

Laisser un commentaire

Nom : (Required)

E-mail : (Required)

Website:

Comment: