Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- //libraries/MY_Form_validation
- class MY_Form_validation extends CI_Form_validation {
- public function errors_array() {
- return $this->_error_array;
- }
- }
- //core/MY_Model
- class MY_Model extends CI_Model {
- protected $validation_rules = [];
- public function __construct() {
- parent::__construct();
- }
- public function validate(array $rulesKeys = null, $returnErrors = false) {
- if (!$rulesKeys) {//skip validation
- return $returnErrors ? [] : true;
- }
- if (!$this->load->is_loaded('form_validation')) {
- $this->load->library('form_validation');
- }
- $rules = array_intersect_key($this->validation_rules, array_flip($rulesKeys));
- foreach ($rules as $rule) {
- $this->form_validation->set_rules(
- $rule['field'],
- $rule['label'],
- $rule['rules'],
- isset($rule['errors']) ? $rule['errors'] : []
- );
- }
- $valid = $this->form_validation->run();
- return $returnErrors ? $this->form_validation->errors_array() : $valid;
- }
- }
- //models/FundsModel
- class FundsModel extends MY_Model {
- protected $validation_rules = [
- 'type' => [
- 'field' => 'funds[type]',
- 'label' => 'Funds type',
- 'rules' => [
- 'required'
- ],
- 'errors' => [
- 'required' => 'Please select funds type'
- ]
- ],
- 'program' => [
- 'field' => 'funds[program]',
- 'label' => 'Funds program',
- 'rules' => [
- 'required'
- ],
- 'errors' => [
- 'required' => 'Please select funds program'
- ]
- ]
- ];
- public function __construct() {
- parent::__construct();
- }
- }
- //controllers/Funds
- class Funds extends PrivateController {
- public function __construct() {
- parent::__construct();
- $this->load->model('FundsModel');
- }
- public function form() {
- $post = $this->input->post();
- if ($post) {
- $rulesKeys = ['type'];
- if (isset($post['funds']['type']) && $post['funds']['type'] == 'program') {
- array_push($rulesKeys, 'program');
- }
- if ($this->FundsModel->validate($rulesKeys)) {
- //save form data, set message and redirect
- }
- }
- $this->load->view('form');
- }
- }
Add Comment
Please, Sign In to add comment