Codeigniter callback dropdown form validation - codeigniter

Just want to validate my codeigniter dropdown form before adding the selected country to database. The problem is that it inserts default value 'selectcountry' into db instead of showing the message "Please choose your country." Please help me :)
Here is My Model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_example extends CI_Model {
function __construct()
{
//Call the Model constructor
parent::__construct();
}
public function did_add() {
$data = array(
'country' => $this->input->post('country')
);
$query = $this->db->insert('example_table', $data);
if ($query) {
return true;}
else {
return false;}
}
}
Here is My View:
$this->load->helper("form","file","html","url");
echo $message;
echo validation_errors();
echo form_open("example/add");
echo form_label("Country:<br>","country");
$data = array(
"selectcountry" => "Select Country",
"CA" => "Canada",
"US" => "United States",
"ZW" => "Zimbabwe"
);
echo form_dropdown('country', $data, 'selectcountry');
echo br(1);
echo form_submit("Submit", "Add");
echo form_close();
Here is My controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Example extends MX_Controller {
public function index() {
$data["message"] = "";
$this->load->view("view_example",$data);
}
public function add() {
$this->load->library('form_validation');
$this->load->model('model_example');
$this->form_validation->set_rules('country', 'Country', 'required|callback_country_check');
if($this->form_validation->run()){
$this->model_example->did_add();
}
else {
$data["message"] = "";
$this->load->view("view_example",$data);
}
}
public function country_check()
{
if ($this->input->post('country') === 'selectcountry') {
$this->form_validation->set_message('country_check', 'Please choose your country.');
return FALSE;
}
else {
return TRUE;
}
}
}

In your view page change this line
$data = array(
"selectcountry" => "Select Country",
"CA" => "Canada",
"US" => "United States",
"ZW" => "Zimbabwe"
);
echo form_dropdown('country', $data, 'selectcountry');
to this
$data = array(
"" => "Select Country",
"CA" => "Canada",
"US" => "United States",
"ZW" => "Zimbabwe"
);
echo form_dropdown('country', $data, set_value('country'));
You wont need another call back function to check if value is empty.

Related

When I Use Query Builder Function then Error message not show

When I Use Query Builder Function in codeIgniter, then Error message not shown.
Here Is a Controller
<?php
class Controller extends CI_Controller
{
public function demo()
{
$this->load->model("Model");
$data["name"] = $this->input->post("text");
$res = $this->Model->add_data($data);
echo $res;
}
}
?>
Here Is a Model
<?php
class Model extends CI_Model
{
public function add_data($data)
{
if ( ! $this->db->insert("table_name",$data))
{
$error = $this->db->error();
return $error["message"];
}
}
}
?>
Try this in your model
$data = array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
);
$sql = $this->db->set($data)->get_compiled_insert('mytable');
echo $sql;
if (!$this->db->simple_query($sql)) {
$error = $this->db->error(); // Has keys 'code' and 'message'
}
echo'<pre>';print_r($error);die;
INSERT INTO mytable (title, name, date) VALUES ('My title', 'My Name', 'My date')
Array
(
[code] => 1146
[message] => Table 'db.mytable' doesn't exist
)
Put this in your model and display it :
In CodeIgniter 3 like #Viren Panchal said, use this : error();
In your example :
$this->db->db_debug = false;
$res = $this->Model->add_data($data);
if(!$res) {
$error = $this->db->error();
echo $error;
}

CakePHP 3.1 : My validation for translate behaviour fields, need some help in review/comment

I have worked on a hook for validate my translated fields, based on this thread : https://stackoverflow.com/a/33070156/4617689. That i've done do the trick, but i'm looking for you guys to help me to improve my code, so feel free to comment and modify
class ContentbuildersTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Tree');
$this->addBehavior('Timestamp');
$this->addBehavior('Translate', [
'fields' => [
'slug'
]
]);
}
public function validationDefault(Validator $validator)
{
$data = null; // Contain our first $context validator
$validator
->requirePresence('label')
->notEmpty('label', null, function($context) use (&$data) {
$data = $context; // Update the $data with current $context
return true;
})
->requirePresence('type_id')
->notEmpty('type_id')
->requirePresence('is_activated')
->notEmpty('is_activated');
$translationValidator = new Validator();
$translationValidator
->requirePresence('slug')
->notEmpty('slug', null, function($context) use (&$data) {
if (isset($data['data']['type_id']) && !empty($data['data']['type_id'])) {
if ($data['data']['type_id'] != Type::TYPE_HOMEPAGE) {
return true;
}
return false;
}
return true;
});
$validator
->addNestedMany('translations', $translationValidator);
return $validator;
}
}
I'm not proud of my trick with the $data, but i've not found a method to get the data of the validator into my nestedValidator...
Important part here is to note that i only rule of my nestedValidator on 'translations', this is very important !
class Contentbuilder extends Entity
{
use TranslateTrait;
}
Here basic for I18ns to work
class BetterFormHelper extends Helper\FormHelper
{
public function input($fieldName, array $options = [])
{
$context = $this->_getContext();
$explodedFieldName = explode('.', $fieldName);
$errors = $context->entity()->errors($explodedFieldName[0]);
if (is_array($errors) && !empty($errors) && empty($this->error($fieldName))) {
if (isset($errors[$explodedFieldName[1]][$explodedFieldName[2]])) {
$error = array_values($errors[$explodedFieldName[1]][$explodedFieldName[2]])[0];
$options['templates']['inputContainer'] = '<div class="input {{type}} required error">{{content}} <div class="error-message">' . $error . '</div></div>';
}
}
return parent::input($fieldName, $options);
}
}
With that formHelper we gonna get the errors of nestedValidation and inject them into the input, i'm not confortable with the templates, so that's why it's very ugly.
<?= $this->Form->create($entity, ['novalidate', 'data-load-in' => '#right-container']) ?>
<div class="tabs">
<?= $this->Form->input('label') ?>
<?= $this->Form->input('type_id', ['empty' => '---']) ?>
<?= $this->Form->input('is_activated', ['required' => true]) ?>
<?= $this->Form->input('translations.fr_FR.slug') ?>
<?= $this->Form->input('_translations.en_US.slug') ?>
</div>
<?php
echo $this->Form->submit(__("Save"));
echo $this->Form->end();
?>
Here my fr_FR.slug is required when type_id is not set to Type::TYPE_HOMEPAGE, yeah my homepage has not slug, note that the en_US.slug is not required at all, because i only required 'translations.xx_XX.xxxx' and not '_translations.xx_XX.xxxx'.
And the last part of the code, the controller
$entity = $this->Contentbuilders->patchEntity($entity, $this->request->data);
// We get the locales
$I18ns = TableRegistry::get('I18ns');
$langs = $I18ns->find('list', [
'keyField' => 'id',
'valueField' => 'locale'
])->toArray();
// Merging translations
if (isset($entity->translations)) {
$entity->_translations = array_merge($entity->_translations, $entity->translations);
unset($entity->translations);
}
foreach ($entity->_translations as $lang => $data) {
if (in_array($lang, $langs)) {
$entity->translation($lang)->set($data, ['guard' => false]);
}
}
Here a .gif of the final result om my side : http://i.giphy.com/3o85xyrLOTd7q0YVck.gif

how to get data from database throught model using codeigniter with for each loop

http error occured while calling data from model using function
model
public function getProductCombo() {
$q = $this->db->get_where('products', array('type' => 'combo'));
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}
controller
function sets() {
$this->sma->checkPermissions();
$this->load->helper('security');
$this->data['error'] = (validation_errors() ? validation_errors() :
$this->session->flashdata('error'));
// problem in this line also
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
$bc = array(array('link' => base_url(),
'page' => lang('home')),
array('link' => site_url('sales'),
'page' => lang('products')),
array('link' => '#', 'page' => "sets")
);
$meta = array('page_title' => "Add Sets", 'bc' => $bc);
$this->page_construct('sales/sets', $meta, $this->data);
}
First of all, No need to include the curly braces for $q->result
foreach ($q->result as $row)
{
$data[] = $row;
}
No need to use validation_errors in your php file.You can directly load your form page.Use validation_errors() in view page.
In your Controller, do this
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
Then in your formpage you can echo
<?php echo validation_errors(); ?>
change this line to
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
this
$this->data['showcombo'] = $this->load->sales_model->getProductCombo();
Because your
model name is
public function getProductCombo()
{
}
Firstly you load model in controller. And then called function, which you have defined in model..
$this->load->model('sales_model','sales'); // sales is alias name of model name
$this->data['showcombo'] = $this->sales->getComboProduct();

CodeIgniter form validation always return false

I've been scouring the webs and potching with my code for hours now and can't seem to figure out why this isn't working.
I have a template library which scans a template.html for {#tags} and then runs the function associated to the tag to create data for that {#tag}'s content and then replaces {#tag} for the content generated, so I can have widget like parts to my template.
On my account/access page I have a login form and a registration form, now when the template library calls the widget_register() function, the form validation doesn't seem to do anything, the data is posted as I can see from the profiler, but the form validation doesn't seem to do anything with it
Account Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Account extends CI_Controller {
public function index()
{
$this->load->helper('url');
#redirect('/');
}
public function access()
{
$this->load->helper('url');
#if($this->auth->loggedin()) redirect('/');
$this->template->compile_page();
}
public function widget_register($template)
{
$this->output->enable_profiler(TRUE);
$this->load->helper('url');
if($this->auth->loggedin()) redirect('/');
if ($this->input->post('register_submit'))
{
$this->load->model('auth_model');
$this->form_validation->set_rules('register_nickname', 'Nickname', 'required|min_length[3]|max_length[75]');
$this->form_validation->set_rules('register_email_address', 'Email Address', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('register_confirm_email_address', 'Confirm Email Address', 'required|valid_email|matches[register_email_address]');
$this->form_validation->set_rules('register_password', 'Password', 'required|min_length[5]');
$this->form_validation->set_rules('register_confirm_password', 'Confirm Password', 'required|min_length[5]|matches[register_password]');
if($this->form_validation->run() !== false)
{
echo 'validation successful';
$nickname = $this->input->post('register_nickname');
$email = $this->input->post('register_email_address');
$generate_salt = $this->auth->generate_keys();
$salt = $generate_salt['1'];
$this->load->library('encrypt');
$generate_password = $salt . $this->input->post('register_password');
$password = $this->encrypt->hash($generate_password);
$generate_series_key = $this->auth->generate_keys();
$user_series_key = $generate_series_key['1'];
$this->db->query('INSERT INTO users (nickname, email, password, salt, register_date) VALUES ( "'.$nickname.'", "'.$email.'", "'.$password.'", "'.$salt.'", "'.time().'")');
}
else
{
echo 'invalid';
echo validation_errors();
}
}
$this->load->helper('form');
$view_data = array();
$view_data['form'] = form_open('account/access');
$view_data['input_nickname'] = form_input(array('name' => 'register_nickname', 'value' => set_value('register_nickname'), 'id' => 'register_nickname', 'class' => 'common_input', 'size' => '55'));
$view_data['input_email'] = form_input(array('name' => 'register_email_address', 'value' => set_value('register_email_address'), 'id' => 'register_email_address', 'class' => 'common_input', 'size' => '55'));
$view_data['input_confirm_email'] = form_input(array('name' => 'register_confirm_email_address', 'value' => '', 'id' => 'register_confirm_email_address', 'class' => 'common_input', 'size' => '55'));
$view_data['input_password'] = form_password(array('name' => 'register_password', 'value' => '', 'id' => 'register_password', 'class' => 'common_input', 'size' => '55'));
$view_data['input_confirm_password'] = form_password(array('name' => 'register_confirm_password', 'value' => '', 'id' => 'register_confirm_password', 'class' => 'common_input', 'size' => '55'));
$view_data['form_submit'] = form_submit('register_submit', 'Register');
$view_data['/form'] = form_close();
$view_data['validation_errors'] = validation_errors('<div class="error-box">', '</div>');
return $this->parser->parse(FCPATH.'themes/'.$this->settings->settings['system_settings']['theme'].'/widgets/'.$template.'.html', $view_data, TRUE);
}
function widget_login()
{
$this->load->helper('url');
// user is already logged in
if ($this->auth->loggedin())
{
return $this->load->view(FCPATH.'themes/'.$this->settings->settings['system_settings']['theme'].'/widgets/login/user.html', '', TRUE);
}
if($this->input->post('register'))
{
redirect('authentication/register');
}
// form submitted
if ($this->input->post('login_email_address') && $this->input->post('login_password'))
{
$this->load->library('form_validation');
$this->load->model('auth_model');
$this->form_validation->set_rules('login_email_address', 'Email Address', 'required|valid_email');
$this->form_validation->set_rules('login_password', 'Password', 'required|min_length[4]');
if($this->form_validation->run() !== false)
{
// validation passed verify from db
$remember = $this->input->post('remember') ? TRUE : FALSE;
if($remember == 'remember');
// check user exists and return user data
$user_data = $this->auth_model->user_exists($this->input->post('email_address'), TRUE);
if($user_data != FALSE)
{
// compare passwords
if ($this->auth_model->check_password($this->input->post('password'), $this->input->post('email_address')))
{
$this->auth->login($user_data->uid, $remember);
redirect('/');
}
else { $this->form_validation->set_custom_error('Incorrect password'); }
}
else { $this->form_validation->set_custom_error('There are no users with that email address'); }
}
}
// show login form
$this->load->helper('form');
$view_data = array();
$view_data['form'] = form_open();
$view_data['input_email'] = form_input('login_email_address', set_value('login_email_address'), 'id="login_email_address"');
$view_data['input_password'] = form_password('login_password', '', 'id="login_password"');
$view_data['input_remember'] = form_checkbox('remember', 'rememberme');
$view_data['form_submit'] = form_submit('login_submit', 'Login');
$view_data['register_button'] = form_submit('register', 'Register');
$view_data['/form'] = form_close();
$view_data['validation_errors'] = validation_errors('<div class="error-box">', '</div>');
return $this->parser->parse(FCPATH.'themes/'.$this->settings->settings['system_settings']['theme'].'/widgets/login/login.html', $view_data, TRUE);
}
function logout()
{
$this->load->helper('url');
$this->session->sess_destroy();
$this->load->helper('cookie');
delete_cookie('aws_session');
delete_cookie('aws_autologin_cookie');
redirect('/');
}
}
and the Template library
class Template {
private $settings;
private $_ci;
private $_controller = ''; # Controller in use
private $_method = ''; # Method in use
private $_is_mobile = FALSE; # Is the User agent a mobile?
private $cache_lifetime = '1';
private $page_output = "";
private $partials = array();
private $spts = array(); # Static page tags
function __construct()
{
$this->_ci =& get_instance();
$this->settings = $this->_ci->settings->settings;
$this->_controller = $this->_ci->router->fetch_class();
$this->_method = $this->_ci->router->fetch_method();
$this->_ci->load->library('user_agent');
$this->_is_mobile = $this->_ci->agent->is_mobile();
log_message('debug', "Template Class Initialized");
}
function build_page()
{
$page = $this->_ci->load->view(FCPATH.'themes/'.$this->settings['system_settings']['theme'].'/pages/'.$this->settings['page_settings']['template'].'.html', '', TRUE);
$this->page_output .= $page;
}
# MAIN PAGE FUNCTIONS END ------------------------------------------------------------------------------------------
public function check_static_tags()
{
if(preg_match_all('/{#[A-Z]{1,75}}/', $this->page_output, $matches))
{
$this->spts = $matches['0'];
$this->spts = array_diff($this->spts, array('{#CONTENT}')); # removes stp_content from array list
return TRUE;
}
return FALSE;
}
# Convert static tags
public function convert_static_tags()
{
foreach($this->spts as $key => $static_tag)
{
$static_tag = str_replace(array('{','}'), '', $static_tag);
$this->partials[$static_tag] = $this->build_widget($static_tag);
}
}
# Convert widget tags
function column_widget_tags()
{
if(preg_match_all('/{#COLUMN_[0-9]{1,11}}/', $this->page_output, $matches))
{
if(isset($this->settings['page_settings']['widgets']))
{
$columns = unserialize($this->settings['page_settings']['widgets']);
}
foreach($columns as $column_id => $widgets)
{
if(count($columns[$column_id]) > '0') // if the column contains widgets
{
$this->partials[''.$this->_stp.'_COLUMN_'.$column_id] = '';
foreach($widgets as $key => $widget_id)
{
// build the widget and add it to the $this->page_bits['column_id'] variable for replacing later in the compiler
$this->partials[''.$this->_stp.'_COLUMN_'.$column_id] .= $this->build_widget($widget_id);
}
}
else
{
$this->partials[''.$this->_stp.'_COLUMN_'.$column_id] = '';
}
}
}
}
# Build Widget
function build_widget($widget_id)
{
if(is_numeric($widget_id))
{
$widget_query = $this->_ci->db->query('SELECT * FROM widgets WHERE id = "'.$widget_id.'"'); # BIND STATEMENTS
}
elseif(preg_match('/#[A-Z]{1,75}/', $widget_id))
{
$widget_query = $this->_ci->db->query('SELECT * FROM widgets WHERE tag = "'.$widget_id.'"'); # BIND STATEMENTS
}
else
{
show_error('Could not get widget from database: '.$widget_id);
}
if($widget_query->num_rows() > 0)
{
$widget_info = $widget_query->row_array();
// loads widgets parent controller, builds the widget (class method) and returns it
$this->_ci->load->controller($widget_info['controller'], $widget_info['controller']);
$method_name = 'widget_'.$widget_info['method'];
$complete_widget = $this->_ci->$widget_info['controller']->$method_name($widget_info['template']);
return $complete_widget;
}
else
{
show_error('The requested widget could not be loaded: '.$widget_id);
}
}
# Replace Partials
function replace_partials()
{
$this->_ci->load->library('parser');
$this->page_output = $this->_ci->parser->parse_string($this->page_output, $this->partials, TRUE);
}
## METADATA
public function prepend_metadata($line)
{
array_unshift($this->_metadata, $line);
return $this;
}
# Put extra javascipt, css, meta tags, etc after other head data
public function append_metadata($line)
{
$this->_metadata[] = $line;
return $this;
}
# Set metadata for output later
public function set_metadata($name, $content, $type = 'meta')
{
$name = htmlspecialchars(strip_tags($name));
$content = htmlspecialchars(strip_tags($content));
// Keywords with no comments? ARG! comment them
if ($name == 'keywords' AND ! strpos($content, ','))
{
$content = preg_replace('/[\s]+/', ', ', trim($content));
}
switch($type)
{
case 'meta':
$this->_metadata[$name] = '<meta name="'.$name.'" content="'.$content.'" />';
break;
case 'link':
$this->_metadata[$content] = '<link rel="'.$name.'" href="'.$content.'" />';
break;
}
return $this;
}
# Embed page into layout wrapper
function layout()
{
$this->_ci->load->helper('html');
$this->append_metadata(link_tag('themes/'.$this->settings['system_settings']['theme'].'/css/layout.css')); # default stylesheet
$this->append_metadata('<link rel="shortcut icon" href="/favicon2.ico" />'); # default favicon
$template['template.title'] = $this->settings['page_settings']['title']; # Page title, can be overidden by the controller ?
$template['template.metadata'] = implode("\n\t\t", $this->_metadata); # Metadata
$template['template.body'] = $this->page_output; # The page
return $this->_ci->parser->parse(FCPATH.'assets/layout/L6_layout_wrapper.html', $template, TRUE);
}
# Run all functions to build page and set in output class
function compile_page($content_data = '')
{
$this->partials['#CONTENT'] = $content_data;
$this->build_page();
$this->column_widget_tags();
if($this->check_static_tags())
{
$this->convert_static_tags();
$this->replace_partials();
}
$output = $this->layout();
$this->_ci->output->set_header('Expires: Sat, 01 Jan 2000 00:00:01 GMT');
$this->_ci->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
$this->_ci->output->set_header('Cache-Control: post-check=0, pre-check=0, max-age=0');
$this->_ci->output->set_header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
$this->_ci->output->set_header('Pragma: no-cache');
# Let CI do the caching instead of the browser
#$this->_ci->output->cache($this->cache_lifetime);
$this->_ci->output->append_output($output);
}
}
Sorry for the incredibly long post, I'm really stumped here and didn't want to miss any code out, thanks in advance!

$db undefined when using model from helper in codeigniter

I want to have a simple helper which records one hit in my database. I have created a $CI instance and attempt to access the model like this...
$CI->load->model('stats_model');
$CI->stats_model->set_hit();
But i get an error in the model..
Severity: Notice
Message: Undefined property: Stats_model::$db
Filename: models/stats_model.php
Line Number: 16
Line 16 is a simple...
$this->db->select('*');
I got the idea to do this from this link http://blog.avinash.com.np/2010/07/01/talk-to-the-database-from-a-helper-codeigniter/
I have tried $CI->db... instead of $this->db in the model but still no luck, any ideas?
HELPER
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
function check_hit() {
//stuff that uses CI
$CI = & get_instance();
$CI->load->library('user_agent');
if ($CI->agent->is_robot()) {
return FALSE;
} else {
//check for a 12 hour cookie
$check = $CI->input->cookie('stat');
if ($check == false) {
//insert a database entry
$CI->load->model('Stats_model');
$CI->Stats_model->set_hit();
//set a cookie
$cookie = array(
'name' => 'stat',
'value' => '1',
'expire' => '43200'
);
// $CI->input->set_cookie($cookie);
}
}
}
check_hit();
?>
MODEL
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Stats_model extends Model {
function Stats_model() {
// Call the Model constructor
parent::Model();
}
function set_hit() {
$date = date('Y-m-d');
$this->db->select('unique_visitors');
$this->db->from('daily_stats');
$this->db->where('date', $date);
$query = $this->db->get();
$date_rows = $query->num_rows();
$result = $query->row();
$visits = $result->unique_visitors;
$visits++;
$data = array(
'unique_visitors' => $visits,
'date' => $date
);
if ($date_rows == 1) {
$this->db->where('date', $date);
$this->db->update('daily_stats', $data);
} else {
$this->db->insert('daily_stats', $data);
}
}
}
?>
This part was a little confusing for me a while back. This seemed to work.
//load the CI instance
$this->ci =& get_instance();
//run a db get
$this->ci->db->get('mytable');

Resources