Tạo form động bằng PHP (ok) class ...
PreviousHàm strlen(), mb_strlen() - Đếm số ký tự trong chuỗi (ok)NextSource Practice php & mysql (ok)
Last updated
Last updated
<?php
define('MSG_ERR_NOTEMPTY', 'Please enter this field');
define('MSG_ERR_EMAIL', 'Please enter correct email address');
class Form {
private $model = 'Model';
public $inputs = array();
public $rules = array(
'email' => array(
'form' => array(
'type' => 'text'
),
'notEmpty' => array(
'rule' => 'notEmpty',
'message'=> MSG_ERR_NOTEMPTY
),
"isEmail" => array(
'rule' => "email",
'message' => MSG_ERR_EMAIL
)
),
'password' => array(
'form' => array(
'type' => 'password'
),
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => MSG_ERR_NOTEMPTY
)
)
);
public function setRules($rules) {
if(!empty($rules)) {
foreach ($rules as $field=> $rule) {
if(isset($rule['form'])) {
$this->inputs[$field] = $rule['form'];
}
}
}
}
public function input($name) {
$type = 'text';
foreach ($this->inputs as $field => $input) {
if($field == $name) {
$type = $input['type'];
$style = isset($input['style']) ? 'style ="'.$input['style'].'"' : '';
switch ($type) {
case 'text':
$inputField = '<input type="text"'.$style.' name="data['.$this->model.']['.$name.']" value="">';
break;
case 'password':
$inputField = '<input type="password"'.$style.' name="data['.$this->model.']['.$name.']" value="">';
break;
}
}
}
echo $inputField;
}
};
$form = new Form();
$form->setRules($form->rules);
$form->input('email');
$form->input('password');
?>