Help understanding codeigniter MVC - tashworth19191 - 11-03-2016
I am trying to build my first codeigniter app, but not understanding how things should link up. I read the documentation and it is not clear.
Here is what I want to do. I have a form in my view that collects data, I want to send the data to the model to insert it into my database.
To do this, what would a simple model view and controller example look like? Also any suggestions on how to learn CI faster would be appreciated.
Thanks, Tom Ashworth
RE: Help understanding codeigniter MVC - Avenirer - 11-04-2016
I would like to point you to my tutorials (http://avenir.ro), but I think the official documentation is still the best.
RE: Help understanding codeigniter MVC - php_rocs - 11-04-2016
While I agree with Avenirer about the documentation, I would also like to mention that there is still a wealth of information about CI on the web (Google: https://www.google.com/?gws_rd=ssl#q=codeigniter+beginner+tutorial&safe=active) and Youtube ( https://www.youtube.com/results?search_query=codeigniter+3+tutorial+beginner ).
RE: Help understanding codeigniter MVC - tashworth19191 - 11-04-2016
Thanks everyone that replied so far! Here is what I am having trouble with, I am using HMVC and I have so far:
routes.php
Code: $route['create_qso'] = 'qso/create_qso';
$route['insert_qso'] = 'qso/insert_qso';
Qso_model.php MODEL
Code: function add_qso($data){
$data = array(
'user_id' => $this->input->post('user_id'),
'date' => $this->input->post('date'),
'time_in_field' => $this->input->post('time-in-field'),
'discipline_id' => $this->input->post('discipline'),
'shift_id' => $this->input->post('shift'),
'type_id' => $this->input->post('type'),
'at_risk_category_id' => $this->input->post('at-risk'),
'at_risk_details' => $this->input->post('at-risk-details'),
'severity_level_id' => $this->input->post('severity-level'));
$this->db->insert('qso', $data);
}
create_qso.php VIEW
Code: <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// logic for form begins
$user_id_val = $this->session->userdata('user_id');
$user_username_val = $this->session->userdata('username');
// discipline dropdown
$disciplines = $this->db->query('SELECT DISTINCT discipline_desc FROM discipline');
$disciplinedropdowns = $disciplines->result();
foreach ($disciplinedropdowns as $disciplinedropdown){
$disciplinedropdownlist[$disciplinedropdown->discipline_desc] = $disciplinedropdown->discipline_desc;
}
$finaldisciplinedropdown = $disciplinedropdownlist;
// shift dropdown
$shifts = $this->db->query('SELECT DISTINCT shift FROM shift');
$shiftdropdowns = $shifts->result();
foreach ($shiftdropdowns as $shiftdropdown){
$shiftdropdownlist[$shiftdropdown->shift] = $shiftdropdown->shift;
}
$finalshiftdropdown = $shiftdropdownlist;
// Type dropdown
$types = $this->db->query('SELECT DISTINCT type FROM type');
$typedropdowns = $types->result();
foreach ($typedropdowns as $typedropdown){
$typedropdownlist[$typedropdown->type] = $typedropdown->type;
}
$finaltypedropdown = $typedropdownlist;
// At Risk dropdown
$atriskcats = $this->db->query('SELECT DISTINCT at_risk_cat FROM at_risk_cat');
$atriskcatdropdowns = $atriskcats->result();
foreach ($atriskcatdropdowns as $atriskcatdropdown){
$atriskcatdropdownlist[$atriskcatdropdown->at_risk_cat] = $atriskcatdropdown->at_risk_cat;
}
$finalatriskdropdown = $atriskcatdropdownlist;
// severity_level dropdown
$severity_levels = $this->db->query('SELECT DISTINCT severity_level FROM severity_level');
$severity_leveldropdowns = $severity_levels->result();
foreach ($severity_leveldropdowns as $severity_leveldropdown){
$severity_leveldropdownlist[$severity_leveldropdown->severity_level] = $severity_leveldropdown->severity_level;
}
$finalseverity_leveldropdown = $severity_leveldropdownlist;
?>
<div class="text-left">
<h1 class="fg-primary f900 text-uppercase">Create QSO</h1>
</div>
<div id="add_qso_form">
<?php echo form_open('create_qso/insert_qso');
echo form_hidden('user_id', $user_id_val); // hiding user id
$date = date("Y-m-d H:i:s"); // getting date in mySQL format
?>
<div class="col-sm-6">
<div class="form-group"> <!-- adding read only date -->
<label for="date">Date</label>
<?php
$datedata = array(
'name' => 'date',
'id' => 'date',
'value' => $date,
'type' => 'datetime',
'class' => 'form-control',
'readonly' => 'true'
);
echo form_input($datedata);
?>
</div>
<div class="form-group"> <!--Adding minutes observed-->
<label for="time-in-field">Minutes Observed</label>
<?php
$timeinfield = array(
'name' => 'time-in-field',
'id' => 'time-in-field',
'value' => '',
'type' => 'number',
'min' => '1',
'max' => '480',
'class' => 'form-control'
);
echo form_input($timeinfield);
?>
</div>
<div class="form-group"> <!--Adding discipline-->
<label for="discipline">Discipline</label>
<?php
$discipline_extras = array(
'class' => 'form-control'
);
echo form_dropdown('discipline',$finaldisciplinedropdown,'',$discipline_extras);
?>
</div>
<div class="form-group"> <!--Adding shift-->
<label for="shift">Shift</label>
<?php
$shift_extras = array(
'class' => 'form-control'
);
echo form_dropdown('shift',$finalshiftdropdown,'',$shift_extras);
?>
</div>
<div class="form-group"> <!--Adding type-->
<label for="type">Type</label>
<?php
$type_extras = array(
'class' => 'form-control'
);
echo form_dropdown('type',$finaltypedropdown,'',$type_extras);
?>
</div>
</div>
<div class="col-sm-6">
<div class="form-group"> <!--Adding At Risk Category-->
<label for="type">At Risk Category</label>
<?php
$at_risk_cat_extras = array(
'class' => 'form-control'
);
echo form_dropdown('at-risk',$finalatriskdropdown,'',$at_risk_cat_extras);
?>
</div>
<div class="form-group"> <!--Adding At Risk Details-->
<label for="time-in-field">At Risk Details</label>
<?php
$timeinfield = array(
'name' => 'at-risk-details',
'id' => 'at-risk-details',
'value' => '',
'type' => 'text',
'class' => 'form-control'
);
echo form_textarea($timeinfield);
?>
</div>
<div class="form-group"> <!--Adding severity_level-->
<label for="severity_level">severity_level</label>
<?php
$severity_level_extras = array(
'class' => 'form-control'
);
echo form_dropdown('severity-level',$finalseverity_leveldropdown,'',$severity_level_extras);
?>
</div>
</div>
<div class="text-center">
<?php
echo form_submit('submit', 'Submit QSO');
echo form_open('create_qso/insert_qso');
?>
</div>
</div>
Create_qso.php CONTROLLER
Code: class Create_qso extends Site_Controller
{
public function __construct()
{
parent::__construct();
//Transfers data to model
$this->load->model('Qso_model'); // load the model
}
public function index() {
// Quick Page setup is the same as $this->load->view() method used in CI
$this->quick_page_setup(Settings_model::$db_config['active_theme'], 'main', 'Create QSO', 'create_qso', 'header', 'footer');
// Setting values for table coloums
}
public function insert_qso() {
$this->Qso_model->add_qso();
$this->load->view('qso/insert_qso');
}
}
When I run this, the form displays great and I can enter data, but when I submit the form I get this:
I can't figure out how to get from the form to insert data into my qso table on my database??? Any help would be appreciated.
Regards, Tom Ashworth
RE: Help understanding codeigniter MVC - cartalot - 11-04-2016
you can't just read the documentation. my suggestion is to -- work -- through the tutorial in the manual. which means that you build the examples in the tutorial at every step and get them working on your server. also suggest that you don't just build things locally and then hope that its going to work on a remote server. i've seen so many people post on stackoverflow because they never took the time to build on a real server. so start building on a remote server as soon as you can.
then if you have an issue or something you don't understand - post your code, and the errors you got. then someone will be able to help you. http://www.codeigniter.com/user_guide/tutorial/index.html
RE: Help understanding codeigniter MVC - Paradinight - 11-04-2016
(11-04-2016, 06:32 AM)php_rocs Wrote: While I agree with Avenirer about the documentation, I would also like to mention that there is still a wealth of information about CI on the web (Google: https://www.google.com/?gws_rd=ssl#q=codeigniter+beginner+tutorial&safe=active) and Youtube ( https://www.youtube.com/results?search_query=codeigniter+3+tutorial+beginner ).
I could post an example code from a beginner tutorial. The example code is garbage and one of the google search result.
Posting a link to google or youtube is not good for learning. Post a link to a good site or book or video.
- http://www.phptherightway.com/
- https://leanpub.com/practicalcodeigniter3
- http://avenir.ro/
@tashworth19191
An example codeigniter page https://github.com/bcit-ci/codeigniter-website
RE: Help understanding codeigniter MVC - InsiteFX - 11-05-2016
If you use Form in your HMVC then you need to have this:
PHP Code: <?php defined('BASEPATH') OR exit('No direct script access allowed');
/** * Class MY_Form_validation * * ./application/libraries/MY_Form_validation.php * * USAGE: * * if ($this->form_validation->run($this) == FALSE) * { * // Load the form view * } * else * { * // Form Success view * } * * So that HMVC can use CI Forms and callbacks. */
class MY_Form_validation extends CI_Form_validation { /** * @var * _ci Super Global */ public $_ci;
/** * run () * --------------------------------------------------------------------------- * * @param string $module * @param string $group * @return bool */ public function run($module = '', $group = '') { (is_object($module)) AND $this->_ci =& $module;
return parent::run($group); }
}
RE: Help understanding codeigniter MVC - tashworth19191 - 11-05-2016
I tried to add that to MY_Form_validation.php and it still gave me the same results. Here is that file to go along with other ones I have posted above:
Code: <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
public function __construct()
{
parent::__construct();
}
/**
*
* is_valid_email: verify validity of e-mail addresses - is also used for AJAX calls
*
* @param string $email the e-mail address to be validated
* @return boolean
*
*/
public function is_valid_email($email) {
if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false) {
$domain = explode("@", $email);
if(checkdnsrr(array_pop($domain), "MX") != false) {
return true;
}
}
return false;
}
/**
*
* is_valid_password: verify whether password is strict enough
*
* @param string $password the password to be validated
* @return boolean
*
*/
public function is_valid_password($password) {
if (preg_match("/[.@#\$\[\]\|\(\)\?\*\+\{\}\!\=\:\-]/", $password) && (strcspn($password, '0123456789') != strlen($password))) {
return true;
}
return false;
}
/**
*
* is_valid_username: verify validity of username against regular expression: a-z, A-Z, 0-9, _, - are allowed
*
* @param string $username the username to be validated
* @return boolean
*
*/
public function is_valid_username($username) {
if (preg_match("/^[a-zA-Z0-9_-]+$/", $username)) {
return true;
}
return false;
}
/**
*
* is_db_cell_available: check for the existence of a unique field within a database table column
*
* @param string $value
* @param string $info a string
* @return boolean
*
*/
public function is_db_cell_available($value, $info) {
list($table, $column) = explode('.', $info, 2);
$this->CI->db->select($column);
$this->CI->db->from(DB_PREFIX . $table);
$this->CI->db->where($column, $value);
$this->CI->db->limit(1);
$query = $this->CI->db->get();
if($query->num_rows() == 0) {
return true;
}
return false;
}
/**
*
* is_db_cell_available_by_id: check for the existence of a unique field within a database table column EXCEPMTING
* the row for which the ID is passed
*
* @param string $value
* @param string $info a string
* @return boolean
*
*/
public function is_db_cell_available_by_id($value, $info) { // do not use for table user (id is user_id)
list($table, $column, $id, $id_column) = explode('.', $info, 4);
if ($id != strval(intval($id))) {return false;}
$this->CI->db->select($column);
$this->CI->db->from(DB_PREFIX . $table);
$this->CI->db->where($column, strtolower($value));
$this->CI->db->where($id_column .' !=', $id);
$this->CI->db->limit(1);
$query = $this->CI->db->get();
if($query->num_rows() == 0) {
return true;
}
return false;
}
/**
*
* check_captcha: verify the reCaptcha answer
*
* @param string $val the input to be validated
* @return boolean
*
*/
function check_captcha($val) {
return $this->CI->recaptchav2->verifyResponse($val); // this is the v2 code, the v1 code is commented out
/*if ($this->CI->recaptcha->check_answer($this->CI->input->ip_address(), $this->CI->input->post('recaptcha_challenge_field'), $val)) {
return true;
}
return false;*/
}
/**
*
* is_member_password: check for the existence of a unique field within a database table column
*
* @param string $password the password to be checked
* @return boolean
*
*/
public function is_member_password($password) {
$this->CI->db->select('nonce, password');
$this->CI->db->from(DB_PREFIX .'users');
$this->CI->db->where('username', $this->CI->session->userdata('username'));
$this->CI->db->limit(1);
$query = $this->CI->db->get();
if($query->num_rows() == 1) {
$this->CI->load->helper('password');
$row = $query->row();
if (hash_password($password, $row->nonce) === $row->password) {
return true;
}
}
return false;
}
/**
* Added this from codeigniter forum input
* @var
* _ci Super Global
*/
public $_ci;
/**
* run ()
* ---------------------------------------------------------------------------
*
* @param string $module
* @param string $group
* @return bool
*/
public function run($module = '', $group = '')
{
(is_object($module)) AND $this->_ci =& $module;
return parent::run($group);
}
}
RE: Help understanding codeigniter MVC - InsiteFX - 11-05-2016
That code should be at the very top of your class and by looking at your code you need to change the $_ci to $CI
RE: Help understanding codeigniter MVC - tashworth19191 - 11-07-2016
(11-05-2016, 10:37 AM)InsiteFX Wrote: That code should be at the very top of your class and by looking at your code you need to change the $_ci to $CI
Thanks for trying to help me, I gave up on trying to keep CodeIgniter as MVC for this and just coded it in PHP in my Controller and View. Like I said I have the back-end login system working fine as HMVC, but trying to add pages, I will just do it as MC for now to get this project finished. I spent 3 days trying to figure this out when I could have done the whole thing in spaghetti code in about a day. Funny, I thought that this MVC thing was supposed to make my life easier
I will keep trying and take a few more tutorials when I am done with this project. I wanted to learn CI because Laravel is too restrictive and I like the freedom CI seems to give me. For instance, if I can't figure out how to do it in CI, I can just hard code everything into the Controller and Veiw, until I figure it out.
Regards, Tom
|