Codeigniter: Not inserting data in table - codeigniter

Update: It is solved ..
For some reason, the data is not getting inserted into the table. It is however being posted from the form as I could see with var dump, but further than that, won't do. So, here are the 3 modules. It is a very simple test scheme: Just a form with two fields, you press Submit and should be inserted. (I can do all that in ordinary PHP with one page, but, the MVC frameworks are a nightmare in this regard, you write about 30 times more code than you would need in procedural.
<?php
class Inserting_controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Inserting_model');
}
public function index ()
{
$this->load->view('inserting_view');
}
// Controller
public function insert()
{
$data = array(
'username' => $this->input->post('username', TRUE),
'password' => sha1($this->input->post('password', TRUE)
));
var_dump($data); // We do get the data posted
exit;
$this->Inserting_model->insertdata($data); // this should forward them to the Model
}
}
?>
==============
MODEL
<?php
class Inserting_model extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->database();
}
public function insertdata($data)
{
$this->db->insert('users', $data);
}
}
?>
========
VIEW
<div id="inserting_form">
<?php echo form_open('index.php/Inserting_controller/insert/'); ?>
<ul>
<li>
<label>Username</label>
<div><?php echo form_input(array('id' => 'username', 'name' => 'username')); ?></div>
</li>
<li>
<label>Password</label>
<div><?php echo form_password(array('id' => 'password', 'name' => 'password')); ?></div>
</li>
<li><?php echo validation_errors();?></li>
<li><?php echo form_submit(array('name' =>'submit'),'Insert');?> </li>
</ul>
<?php echo form_close(); ?>
</div>

Blushing :/
On writing the debugging code, I forgot to delete the exit; thus, the program exited right after that ....

Related

Yii2 client validation does not work

I have clean yii2-advanced template installed. I created a table in DB with id and test fields. In my Model I wrote rule:
public function rules()
{
return [
[['test'], 'required'],
];
}
Also I specified an unique id for my form.
But validation does not work. After typing smth to control and focus out I have an error in console: Uncaught TypeError: Cannot read property 'required' of undefined. What can be a reason of this?
EDIT:
Model:
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
class ContactForm extends Model
{
public $name;
public function rules()
{
return [
[['name'], 'required'],
];
}
}
View:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
<div class="site-contact">
<div class="row">
<div class="col-lg-6">
<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
<?= $form->field($model, 'name')->textInput() ?>
<?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
Controller action:
use backend\models\ContactForm;
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post())) {
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
When you use Rules(), you must type the attribute (or array of attributes) first, and then the type of rule (that can be also a custom function by the way):
[['name'], 'required'] // setting the attribute "name" as required
you can read more about validation and rules here
if you have applied unique id for your form field, try removing it, Yii2 generates id by itself and applies validation message accordingly.

Load table from database to dropdown CodeIgniter

I have trouble with loading the table to the form_dropdown. I have tried any solution from the same trouble with me but its not working.
Here's the controller code:
<?php
class Registrasi extends Superuser_Controller
{
public $data = array(
'halaman' => 'registrasi',
'main_view' => 'program/administrasi/registrasi_list',
'title' => 'Data Registrasi',
);
public function __construct()
{
parent::__construct();
$this->load->model('program/administrasi/Registrasi_model', 'registrasi_model');
}
public function index()
{
$registrasi = $this->registrasi_model->get_all_registrasi_data();
$this->data['registrasiData'] = $registrasi;
$this->load->view($this->layout, $this->data);
}
public function tambah()
{
$this->data['namaNegara'] = $this->registrasi_model->get_nama_negara();
$this->data['main_view'] = 'program/administrasi/registrasi_form';
$this->data['form_action'] = site_url('program/administrasi/registrasi/tambah');
// Data untuk form.
if (! $_POST) {
$registrasi = (object) $this->registrasi_model->default_value;
} else {
$registrasi = $this->input->post(null, true);
}
// Validasi.
if (! $this->registrasi_model->validate('form_rules')) {
$this->data['values'] = (object) $registrasi;
$this->load->view($this->layout, $this->data);
return;
}
}
}
Here's the model code:
<?php
class Registrasi_model extends MY_Model
{
protected $_tabel = 'tb_registrasi';
protected $form_rules = array(
array(
'field' => 'Negara_Tujuan',
'label' => 'Negara Tujuan',
'rules' => 'trim|xss_clean|required|max_length[50]'
)
);
public $default_value = array(
'Negara_Tujuan' => ''
);
public function get_nama_negara()
{
$query = $this->db->query('SELECT Nama_Negara FROM tb_negara_tujuan');
return $query->result();
}
}
Here's the view code:
<div class="container">
<h2>Form Registrasi</h2>
<hr>
<?php echo form_open($form_action, array('id'=>'myform', 'class'=>'myform', 'role'=>'form')) ?>
<div class="container">
<div class="row">
<div class="form-group has-feedback <?php set_validation_style('Negara_Tujuan')?>">
<?php echo form_label('Negara Tujuan', 'negara_tujuan', array('class' => 'control-label')) ?>
<?php
foreach($namaNegara as $row)
{
echo form_dropdown('NegaraTujuan', $row->Nama_Negara);
}
?>
<?php set_validation_icon('Negara_Tujuan') ?>
<?php echo form_error('Negara_Tujuan', '<span class="help-block">', '</span>');?>
</div>
<?php echo form_button(array('content'=>'Simpan', 'type'=>'submit', 'class'=>'btn btn-primary', 'data-confirm'=>'Anda yakin akan menyimpan data ini?')) ?>
</div>
</div>
<?php echo form_close() ?>
</div>
The trouble I'm having is: Invalid argument supplied for foreach()
Your controller code must be :-
public function tambah()
{
$namaNegara[''] = 'select a option';
$namaNegaras = $this->registrasi_model->get_nama_negara();
foreach($namaNegaras as $namaNegaranew)
{
$namaNegara[$namaNegaranew->id] = $namaNegaranew->Nama_Negara ;
}
$this->data['namaNegara'] = $namaNegara;
$this->data['main_view'] = 'program/administrasi/registrasi_form';
$this->data['form_action'] = site_url('program/administrasi/registrasi/tambah');
// Data untuk form.
if (! $_POST) {
$registrasi = (object) $this->registrasi_model->default_value;
} else {
$registrasi = $this->input->post(null, true);
}
// Validasi.
if (! $this->registrasi_model->validate('form_rules')) {
$this->data['values'] = (object) $registrasi;
$this->load->view($this->layout, $this->data);
return;
}
}
And in view in place of
<?php
foreach($namaNegara as $row)
{
echo form_dropdown('NegaraTujuan', $row->Nama_Negara);
}
?>
Simply use
<?php echo form_dropdown('NegaraTujuan', $namaNegara , set_value('NegaraTujuan')); ?>
I think i have the answer for my problem:
Controller code (still same, no change whatsoever)
Model code: change the function into
public function get_nama_negara()
{
$query = $this->db->query('SELECT Nama_Negara FROM tb_negara_tujuan');
$dropdowns = $query->result();
foreach ($dropdowns as $dropdown)
{
$dropdownlist[$dropdown->Nama_Negara] = $dropdown->Nama_Negara;
}
$finaldropdown = $dropdownlist;
return $finaldropdown;
}
View code:
<div class="container">
<h2>Form Registrasi</h2>
<hr>
<?php echo form_open($form_action, array('id'=>'myform', 'class'=>'myform', 'role'=>'form')) ?>
<div class="container">
<div class="row">
<div class="form-group has-feedback <?php set_validation_style('Negara_Tujuan')?>">
<?php echo form_label('Negara Tujuan', 'negara_tujuan', array('class' => 'control-label')) ?>
<?php echo form_dropdown('NegaraTujuan', $namaNegara, set_value('NegaraTujuan'), 'class="dropdown"'); ?>
<?php set_validation_icon('Negara_Tujuan') ?>
<?php echo form_error('Negara_Tujuan', '<span class="help-block">', '</span>');?>
</div>
<?php echo form_button(array('content'=>'Simpan', 'type'=>'submit', 'class'=>'btn btn-primary', 'data-confirm'=>'Anda yakin akan menyimpan data ini?')) ?>
</div>
</div>
<?php echo form_close() ?>
</div>

Yii2 Session, Flash messages

I have a problem with setting flash messages.
So, i have an action which in some cases should redirect with flash. It looks like this:
if(!$this->_isSameOrg($reports)){
\Yii::$app->session->setFlash('consol_v_error',\Yii::t('app/consol', 'some_text'));
$this->redirect(\Yii::$app->request->getReferrer());
return;
}
After redirect in view i have this
<div class="col-lg-12">
<?php if(Yii::$app->session->hasFlash('consol_v_error')): ?>
<div class="alert alert-danger" role="alert">
<?= Yii::$app->session->getFlash('consol_v_error') ?>
</div>
<?php endif; ?>
</div>
The problem is i don't see any message here. In Debug panel i see SESSION var populated with good flash, but it doesn't display with this if-statement.
Maybe i need to configure session component or something?...
To set flash,try like
\Yii::$app->getSession()->setFlash('error', 'Your Text Here..');
return $this->redirect('Your Action');
And to display it..
<?= Yii::$app->session->getFlash('error'); ?>
you can try like this
<?php
foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
echo '<div class="alert alert-' . $key . '">' . $message . '</div>';
}
?>
Simply do:
Add two strings to: /views/layout/main.php
in block use:
use frontend\widgets\Alert;
before <?= $content ?>:
<?= Alert::widget() ?>
Now all messages automatically will be on screen. Lets try it! Add in any controller's method:
Yii::$app->session->setFlash('warning', 'bla bla bla bla 1');
Yii::$app->session->setFlash('success', 'bla bla 2');
Yii::$app->session->setFlash('error', 'bla bla 3');
Instead of this:
$this->redirect(\Yii::$app->request->getReferrer());
return;
try this:
return $this->redirect(\Yii::$app->request->getReferrer());
It's working fine for me.
in yii2 flash can be set like this
Yii::$app->session->setFlash('success', 'Thank you ');
Here is my solution:
overwrite standart Session class:
namespace app\components;
use Yii;
class Session extends \yii\web\Session {
public function getAllFlashesNormalized() {
$flashes = [];
foreach (Yii::$app->session->getAllFlashes() as $key => $flash) {
if (is_array($flash))
foreach ($flash AS $message)
$flashes[] = ['key' => $key, 'message' => $message];
else
$flashes[] = ['key' => $key, 'message' => $flash];
}
return $flashes;
}
}
So you can:
Yii::$app->session->addFlash('success', 'Text.');
Yii::$app->session->addFlash('success', 'Another text.');
And output this messages:
<?php foreach (Yii::$app->session->getAllFlashesNormalized() as $flash) { ?>
<div class="alert alert-<?=$flash['key']?>" role="alert"><?=$flash['message']?></div>
<?php } ?>
in my case flash message deleted after redirect, when i use hasFlash before redirect.
if (!Yii::$app->getSession()->hasFlash('success')) {
Yii::$app->getSession()->setFlash('success', Yii::t('app', 'your text'));
}
So i added this and it helped
if (!Yii::$app->getSession()->hasFlash('success')) {
Yii::$app->getSession()->setFlash('success', Yii::t('app', 'your text'));
} else {
Yii::$app->getSession()->set('__flash', array('success' => -1));
}
Did not work for me.
I'd rather use:
In the controler:
$session = new Session;
$session->addFlash("warning","Your text here");
In the view :
<?php
$session = new Session;
foreach ($session->getAllFlashesNormalized() as $flash) {
?>
<div class="alert alert-<?=$flash['key']?>" role="alert">
<?=$flash['message']?>
</div>
<?php
}
?>

How do I get domPDF to display my codeigniter view correctly

I feel there is a small step that I am missing that apparently everyone on the other related questions understands.
I have created a simple CI 2 view, controller and model, shown below:
I have installed dompdf into the helpers folder like so:
applications/helpers/dompdf
applications/helpers/dompdf/dompdf_help.php
What I want to happen is when user clicks the submit button on the view page, send form data to the db, then get a pdf of that filled in form.
Between getting underdefined var errors or nothing at all, except for the data going to db, I can't see what I am missing.
Could some please guide me? What am I not getting here?
View
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>test pdf</title>
</head>
<body>
<?php // Change the css classes to suit your needs
$attributes = array('class' => '', 'id' => '');
echo form_open('quicksubmit', $attributes); ?>
<p>
<label for="title">Title <span class="required">*</span></label>
<?php echo form_error('title'); ?>
<?php // Change the values in this array to populate your dropdown as required ?>
<?php $options = array(
'' => 'Please Select',
'Mrs' => 'Mrs',
'Miss' => 'Miss',
'Ms' => 'Ms',
'Mr' => 'Mr',
); ?>
<br /><?php echo form_dropdown('title', $options, set_value('title'))?>
</p>
<p>
<label for="first_name">First Name</label>
<?php echo form_error('first_name'); ?>
<br /><input id="first_name" type="text" name="first_name" maxlength="100" value="<?php echo set_value('first_name'); ?>" />
</p>
<p>
<label for="last_name">Last Name <span class="required">*</span></label>
<?php echo form_error('last_name'); ?>
<br /><input id="last_name" type="text" name="last_name" maxlength="100" value="<?php echo set_value('last_name'); ?>" />
</p>
<p>
<label for="branch">Branch</label>
<?php echo form_error('branch'); ?>
<?php // Change the values in this array to populate your dropdown as required ?>
<?php $options = array(
'' => 'Please Select',
'Branch 1' => 'Branch One',
'Branch 2' => 'Branch Two',
); ?>
<br /><?php echo form_dropdown('branch', $options, set_value('branch'))?>
</p>
<p>
<label for="zip">Zip</label>
<?php echo form_error('zip'); ?>
<br /><input id="zip" type="text" name="zip" maxlength="7" value="<?php echo set_value('zip'); ?>" />
</p>
<p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php echo form_close(); ?>
</body>
</html>
Controller
<?php
class Quicksubmit extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->database();
$this->load->helper('form');
$this->load->helper('url');
$this->load->model('quicksubmit_model');
}
function index()
{
$this->form_validation->set_rules('title', 'Title', 'required|trim|xss_clean|max_length[50]');
$this->form_validation->set_rules('first_name', 'First Name', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('branch', 'Branch', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('zip', 'Zip', 'trim|xss_clean|is_numeric|max_length[7]');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('quicksubmit_view');
}
else // passed validation proceed to post success logic
{
// build array for the model
$this->pdf($output);
$form_data = array(
'title' => set_value('title'),
'first_name' => set_value('first_name'),
'last_name' => set_value('last_name'),
'branch' => set_value('branch'),
'zip' => set_value('zip')
);
// run insert model to write data to db
if ($this->quicksubmit_model->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
{
redirect('quicksubmit/success'); // or whatever logic needs to occur
}
else
{
echo 'An error occurred saving your information. Please try again later';
// Or whatever error handling is necessary
}
}
}
function success()
{
redirect(base_url(),'refresh');
/*echo 'this form has been successfully submitted with all validation being passed. All messages or logic here. Please note
sessions have not been used and would need to be added in to suit your app';*/
}
function pdf()
{
$this->load->helper(array('dompdf', 'file'));
// page info here, db calls, etc.
$html = $this->load->view('quicksubmit_view', $data, true);
pdf_create($html, 'filename');
/*or
$data = pdf_create($html, '', false);
write_file('name', $data);*/
//if you want to write it to disk and/or send it as an attachment
}
}
?>
Model
<?php
class Quicksubmit_model extends CI_Model {
function __construct()
{
parent::__construct();
}
// --------------------------------------------------------------------
/**
* function SaveForm()
*
* insert form data
* #param $form_data - array
* #return Bool - TRUE or FALSE
*/
function SaveForm($form_data)
{
$this->db->insert('quicksubmit', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
return FALSE;
}
}
?>
dompdf_help.php file
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function pdf_create($html, $filename='', $stream=TRUE)
{
require_once("dompdf/dompdf_config.inc.php");
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
if ($stream) {
$dompdf->stream($filename.".pdf");
} else {
return $dompdf->output();
}
}
?>
you were nearly there!
It is probably better to store dompdf in the third_party folder, and it is not a code igniter helper. - see the path i store it in in the constructor. Then it is always available.
Also, it is probably better to do the 'work' of the program in the model, so this includes making PDFs etc.
don't use a ?> at the end of your code.
i modded your code to work, and verified it did work. it simply saves a file named tmp/name.pdf. I am sure you can work out the rest. i did comment out the database loader because that wasn't needed for me to test the code.
see enc.
<?php
class Quicksubmit extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
//$this->load->database();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('file');
$this->load->model('quicksubmit_model');
global $_dompdf_show_warnings;global $_dompdf_debug;global $_DOMPDF_DEBUG_TYPES;global $_dompdf_warnings;$_dompdf_show_warnings = FALSE;
require_once(realpath(APPPATH."third_party/dompdf")."/dompdf_config.inc.php"); // remember that the constant DOMPDF_TEMP_DIR may need to be changed.
spl_autoload_register('DOMPDF_autoload');
}
function index()
{
$this->form_validation->set_rules('title', 'Title', 'required|trim|xss_clean|max_length[50]');
$this->form_validation->set_rules('first_name', 'First Name', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('branch', 'Branch', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('zip', 'Zip', 'trim|xss_clean|is_numeric|max_length[7]');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('quicksubmit_view');
}
else // passed validation proceed to post success logic
{
// build array for the model
$form_data = array(
'title' => set_value('title'),
'first_name' => set_value('first_name'),
'last_name' => set_value('last_name'),
'branch' => set_value('branch'),
'zip' => set_value('zip')
);
$this->pdf($form_data);
// run insert model to write data to db
if ($this->quicksubmit_model->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
{
redirect('quicksubmit/success'); // or whatever logic needs to occur
}
else
{
echo 'An error occurred saving your information. Please try again later';
// Or whatever error handling is necessary
}
}
}
function success()
{
redirect(base_url(),'refresh');
/*echo 'this form has been successfully submitted with all validation being passed. All messages or logic here. Please note
sessions have not been used and would need to be added in to suit your app';*/
}
function pdf($data)
{
$dompdf = new DOMPDF();
$html = $this->load->view('quicksubmit_view', $data, true);
$dompdf->set_paper('a4','portrait');
$dompdf->load_html($html);
$dompdf->render();
$pdf = $dompdf->output();
write_file('tmp/name.pdf', $pdf);
}
}

How to use ajax with codeigniter's modules

I have a page written in codeigniter framework.
Now I want to add a button to page (eg 'show more') that will get data with 'ajax.php' from the database and display them on the site, but I do not want it separately connect to the database and then get the results, just want to be able to collect data (in ajax.php) as well as in codeigniter controllers (using models)...
Hope you understand me :)
Here you go just add view more button and call this js and ajax function..This is code i have used please see it and use it as per your requirment
$('.more').live("click",function()
{
var this_tag = $(this);
var ID = $(this).attr("id");
if(ID)
{
$("ol#updates").addClass('tiny-loader');
this_tag.html('Loading.....');
$.post(siteUrl+"ajax/ajax_more",{lastmsg:ID,restid:$(this_tag).data("restid")},function(html){
$("ol#updates").removeClass('tiny-loader');
$("ol#updates").append(html);
$("#more"+ID).remove();// removing old view-more button
});
}
else
{
this_tag.fadeOut('slow');// no results
}
return false;
});
code in ajax file
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax_more extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('general_model');
$this->limit =REVIEW_DETAIL;
}
public function index($offset = 0)
{
$lastmsg=$this->input->post('lastmsg');
$rest_id=$this->input->post('restid');
$value=('reviews.*,usermaster.Name as User');
$joins = array
(
array
(
'table' => 'tk_usermaster',
'condition' => 'usermaster.Id = reviews.UserId',
'jointype' => 'leftouter'
),
);
$this->results = $this->general_model->get_joinlist('reviews',$value,$joins,array('reviews.Status'=>'Enable','reviews.RestaurantId'=>$rest_id,'reviews.Id <'=>$lastmsg),'reviews.Id','desc',$this->limit,$offset);
$data['list_review']= $this->results['results'];
?>
<?php foreach ($data['list_review'] as $row): ?>
<div class="user_reviews_data" >
<div class="width-20 float-left">
<span class="padleft-10"><?php echo $row->User; ?> </span>
<br/>
<span class="padleft-10 "><div class="rateit" data-rateit-value="<?php echo $row->Rating;?>" data-rateit-ispreset="true" data-rateit-readonly="true"></div></span>
<div class="muted padleft-10 float-left"><small><?php echo date('dS M Y' ,strtotime($row->CreatedDate)); ?></small></div>
</div>
<div class="width-80 float-left"><?php echo $row->Feedback;?></div>
<span class="report_span">Report this Feedback <img src="<?php echo base_url();?>themes/images/FLAG_GREY.png"></span>
</div>
<?php
$msg_id = $row->Id;
endforeach; ?>
</div>
<div id="more<?php echo #$msg_id; ?>" class="btn-container center_text morebox">
View More
</div>
<?php
}
}

Resources