CodeIgniter insert into two tables - codeigniter

This is my model and i have problem when i go create "pjesma", i choose "izvodjac" in the form, and how to implement this with codeigniter3, i have to insert values into "izvodi_pjesmu", from where do i get "pjesma_id" that i am just inserting, i hope its clear, if you see the EER diagram below you will understand i hope. Thank you.
diagram
controller method:
public function kreiraj()
{
if (isset($_POST['kreiraj']))
{
$data1 = array(
'naslov' => $this->input->post('naslov'),
'tablatura' => $this->input->post('tablatura'),
'korisnik_korisnik_id' => $_SESSION['korisnik_id']
);
$data2 = array(
'izvodjac_izvodjac_id' => $this->input->post('izvodjaci')
);
$this->form_validation->set_rules('izvodjaci','Izvođači','required|callback_check_default');
$this->form_validation->set_message('check_default', 'Morate odabrati izvođača');
$this->form_validation->set_rules('naslov', 'Naslov', 'required', array('required' => 'Naslov je obavezan'));
$this->form_validation->set_rules('tablatura', 'Tablatura', 'required', array('required' => 'Tablatura je obavezna'));
if ($this->form_validation->run() != FALSE)
{
$this->pjesma_model->kreiraj($data1, $data2);
redirect('pjesma', 'location');
}
}
$data['izvodjaci'] = $this->izvodjac_model->svi_izvodjaci();
$this->load->view('zaglavlje');
$this->load->view('pjesma_kreiraj', $data);
$this->load->view('podnozje');
}
model method:
public function kreiraj($data1, $data2)
{
$this->db->insert('izvodi_pjesmu', $data2);
$this->db->insert('pjesma', $data1);
}
view:
<h1>Kreiranje pjesme</h1>
<hr>
<div class="row">
<div class="col"></div>
<div class="col-9">
<?php if (validation_errors()): ?>
<div class="alert alert-info">
<?php echo validation_errors(); ?>
</div>
<?php endif; ?>
<?php echo form_open('pjesma/kreiraj'); ?>
<div class="form-group">
<label for="izvodjaci">Izvođač:</label>
<select class="form-control" name="izvodjaci" id="izvodjaci">
<option value="0">odabir izvođača</option>
<?php foreach($izvodjaci as $izvodjac): ?>
<option value="<?php echo $izvodjac->izvodjac_id; ?>"><?php echo $izvodjac->naziv; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="naslov">Naslov:</label>
<input type="text" class="form-control" id="naslov" name="naslov" value="<?php echo set_value('naslov'); ?>" />
</div>
<div class="form-group">
<label for="tablatura">Tablatura:</label>
<textarea class="form-control" id="tablatura" name="tablatura"></textarea>
</div>
<button type="submit" class="btn btn-default" name="kreiraj">Kreiraj pjesmu</button>
<?php echo form_close(); ?>
</div>
<div class="col"></div>

Try this:
Controller:
public function kreiraj()
{
if (isset($_POST['kreiraj']))
{
$data1 = array(
'naslov' => $this->input->post('naslov'),
'tablatura' => $this->input->post('tablatura'),
'korisnik_korisnik_id' => $_SESSION['korisnik_id']
);
$this->form_validation->set_rules('izvodjaci','Izvođači','required|callback_check_default');
$this->form_validation->set_message('check_default', 'Morate odabrati izvođača');
$this->form_validation->set_rules('naslov', 'Naslov', 'required', array('required' => 'Naslov je obavezan'));
$this->form_validation->set_rules('tablatura', 'Tablatura', 'required', array('required' => 'Tablatura je obavezna'));
if ($this->form_validation->run() != FALSE)
{
$id= $this->pjesma_model->kreiraj($data1);
$data2 = array(
'izvodjac_izvodjac_id' => $this->input->post('izvodjaci'),
'pjesma_pjesma_id' => $id
);
$this->pjesma_model->pjesma_pjesmu($data2);
redirect('pjesma', 'location');
}
}
$data['izvodjaci'] = $this->izvodjac_model->svi_izvodjaci();
$this->load->view('zaglavlje');
$this->load->view('pjesma_kreiraj', $data);
$this->load->view('podnozje');
}
Model:
public function kreiraj($data1)
{
$this->db->insert('pjesma', $data1);
return $this->db->insert_id();
}
public function pjesma_pjesmu($data)
{
$this->db->insert('izvodi_pjesmu', $data);
return $this->db->insert_id();
}

You can use $this->db->insert_id();
Which will return the last inserted id. Add this line after inserting data in pjesma table which will return 'pjesma_id'. Then you can use it.
Like this -
public function kreiraj($data1, $data2)
{
$this->db->insert('pjesma', $data1);
// ge tlast inserted id
$pjesma_id = $this->db->insert_id();
$izvodjac_izvodjac_id = $data2['izvodjac_izvodjac_id'];
$data = array( 'pjesma_id' => $pjesma_id,
'izvodjac_izvodjac_id' => $izvodjac_izvodjac_id );
$this->db->insert('izvodi_pjesmu', $data);
}

You can do this thing like this, may be this will helps you,
$insert = array(
'naslov' => $this->input->post('naslov'),
'tablatura' => $this->input->post('tablatura'),
'korisnik_korisnik_id' => $_SESSION['korisnik_id']
);
$this->db->insert('tabl1', $insert);
$output["insert_id"] = $this->db->insert_id();
if (isset($output["insert_id"])) {
$insert = array(
'field1' => $value1,
'field2' => $value2,
);
$this->db->insert('tabl2', $insert);
}

Related

Yii2 conditional validation on radio box

I'm trying to use conditional validation on a attribute account_no. It should be validate only when I select the value 'old' in the attribute account_version. But it is not working. The error I'm getting is validation is required for newalso. Should I use javascript instead to validate
My code in model
return [
['account_no', 'required', 'when' => function($model) {
return $model->account_version == 'Old';
}],
]
My code in form
<?php if ($model->isNewRecord) {?>
<div class="row">
<div class="col-md-2">
<label for="">Account Version</label>
</div>
<div class="col-md-2">
<?php echo $form->field($model, 'account_version')->radioList(['New'=>'New','Old'=>'Old'])->label(false); ?>
</div>
<div id="action_block" class="col-md-6">
<div class="col-md-3">
<label for="">Account No:</label>
</div>
<div class="col-md-3">
<?= $form->field($model, 'account_no')->textInput(['maxlength' => true])->label(false) ?>
</div>
</div>
</div>
<?php } ?>
Model
[['account_no'], 'required', 'when' => function ($model) { return $model->account_version == 'Old'; }, 'whenClient' => "function (attribute, value) { return $('#modelName[account_version]').val() == 'Old'; }"],
Form
<?php $form = ActiveForm::begin(['id' => 'account-form', 'enableAjaxValidation' => true]); ?>
Controller
if($model->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return yii\widgets\ActiveForm::validate($model);
}
}
<?php
return [
['account_no', 'required', 'when' => function ($model) {
return $model->account_no == 'Old';
}, 'whenClient' => "function (attribute, value) {
return $('#account_no').val() == 'Old';
}"]
]
?>
http://www.yiiframework.com/doc-2.0/guide-input-validation.html [reference links]

Input image in Yii2 Dynamic Form always null

I want to make dynamic input that save an image to my website.
I use yii2-dynamicform and Kartik input file extension. But, it always save it as null.
Thank you for your help
Ps : ... is other part of my code that not relevant with this question. :)
In controller :
<?php
namespace frontend\controllers;
use Yii;
use common\models\Election;
use common\models\ElectionSearch;
use common\models\Model;
use common\models\Kandidat;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\ActiveDataProvider;
use yii\web\Session;
use yii\web\UploadedFile;
use yii\helpers\ArrayHelper;
class ElectionController extends Controller
{
...
public function actionCreate()
{
$model = new Election();
$modelsKandidat = [new Kandidat];
if ($model->load(Yii::$app->request->post())){
$model->save();
$modelsKandidat = Model::createMultiple(Kandidat::classname());
Model::loadMultiple($modelsKandidat, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsKandidat) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsKandidat as $modelKandidat) {
$modelKandidat->id_election = $model->id_election;
if($modelKandidat->file = UploadedFile::getInstance($modelKandidat,'file'))
{
$imageName = date('dmyhis_').$modelKandidat->id_election;
$modelKandidat->file->saveAs('../../common/file/fotokandidat/'.$imageName.'.'.$modelKandidat->file->extension);
$modelKandidat->foto = $imageName.'.'.$modelKandidat->file->extension;
}
if (! ($flag = $modelKandidat->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id_election]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
} else {
return $this->render('create', [
'model' => $model,
'modelsKandidat' => $modelsKandidat,
]);
}
}
...
}
In _form :
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\file\FileInput;
use yii\helpers\ArrayHelper;
use dosamigos\datepicker\DatePicker;
use wbraganca\dynamicform\DynamicFormWidget;
?>
<div class="election-form">
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data', 'id' => 'dynamic-form']]); ?>
...
<!-- mulai input kandidat !-->
<div class="row">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i>Vote</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsKandidat[0],
'formId' => 'dynamic-form',
'formFields' => [
'nama',
'deskripsi',
'riwayat',
'file',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsKandidat as $i => $modelsKandidat): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Kandidat</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelsKandidat->isNewRecord) {
echo Html::activeHiddenInput($modelsKandidat, "[{$i}]id_kandidat");
}
?>
<div class="row">
<div class="col-sm-4">
<?= $form->field($modelsKandidat, "[{$i}]nama")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelsKandidat, "[{$i}]deskripsi")->textarea(['rows' => 6]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelsKandidat, "[{$i}]riwayat")->textarea(['rows' => 6]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelsKandidat, "[{$i}]file")->fileInput() ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
<!-- selesai input kandidat !-->
...
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
It's from #shoara/#zahraj answer :
I think you forgot to specify index for your file `
foreach ($modelsKandidat as $keyindex=>$modelKandidat)
{
$modelKandidat->id_election = $model->id_election;
if ($modelKandidat->file = UploadedFile::getInstance($modelKandidat, "[{$keyindex}]file")) {
.......
}
}
see demo controller and form part,imagine $modelCatalogOption in demo is your $model = new Election(); and $modelsOptionValue is your $modelsKandidat = [new Kandidat]; if you try and check your values in your controller I'm sure you can solve this problem easily. Pay attention to actionCreate

codeigniter login validation not validating rules

am using codeigniter 3.0.4 .here this Here the action send to the controler(first.php)not validating anything it will turn to else statement and display login page again(as set as in redirect('welcome/login_page');). my register function in the same controller working good. what is the exact problem ..please help me to find it.thanks.
..............the controller(first.php).....
public function signup_validation(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|valid_email|callback_validate_credentials');
$this->form_validation->set_rules('password', 'Password', 'required|md5|trim');
if($this->form_validation->run() ){
$user_id= $this->model_users->get_id($this->input->post('email'));
$user_status = $this->model_users->get_status($this->input->post('email'));
$data = array (
'user_id' => $user_id,
'email' => $this->input->post('email'),
'user_status' =>$user_status,
'is_logged_in' => 1
);
$this->session->set_userdata($data);
}
if ($this->session->userdata('user_status')=='0') {
redirect('main/admins');
}
elseif ($this->session->userdata('user_status')=='1') {
redirect('main/members');
}else{
redirect('welcome/login_page');
}
}
public function validate_credentials(){
$this->load->model('model_users');
if($this->model_users->can_log_in() ){
return TRUE;
} else {
$this->form_validation->set_message('validate_credentials', 'Invalid useername(email-id) or password. !');
return FALSE;
}
}
....the view(login.php)......
echo form_open("first/signup_validation");
echo'<div class="row">';
echo'<div class="form-group col-md-6 col-xs-12 col-sm-6">';
echo'<label for="email">Email<span></span></label>';
echo'<input type="text" class="form-control" id="email">';
echo'</div>';
echo'<div class="form-group col-md-6 col-xs-12 col-sm-6">';
echo'<label for="password">Password<span></span></label>';
echo'<input type="password" class="form-control" id="password">';
echo'</div>';
echo'</div>';
$data2 = array(
'class' => 'btn btn-default',
);
echo form_submit($data2, 'Login');
echo form_close('');
?>
echo '<input type="text" class="form-control" id="email">';
Your input elements don't contain a name attribute. The name is what's used as the identifier in the validation rule.
$this->form_validation->set_rules('email'... // <- 'email' is the name attribute
Do this...
echo'<input type="text" class="form-control" id="email" name="email">';

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>

Saving data from a drop down list in CodeIgniter

I created a menu page where it has a drop down menu with a list of menus from the database and it also has a textbox to enter new menus.
The problem I'm having is that I can't seem to figure out how to save my dropdown. So for example I have a menu called "About Us" in the drop down list and I want to create a new menu called "Team", and "Team" is a child of "About Us"
So in my table I would have something like this
id | parent | title
------------------------
1 | NULL | About Us
2 | 1 | Team
Menu Controller
function get_data_from_post()
{
$data['title'] = $this->input->post('title', TRUE);
$data['parent'] = $this->input->post('parent', TRUE);
if(!isset($data)){
$data = '';
}
return $data;
}
function get_data_from_db($update_id)
{
$query = $this->get_where($update_id);
foreach($query->result() as $row){
$data['title'] = $row->title;
$data['parent'] = $row->parent;
}
return $data;
}
function create()
{
$update_id = $this->uri->segment(3);
$submit = $this->input->post('submit', TRUE);
if($submit == "Submit"){
//person has submitted the form
$data = $this->get_data_from_post();
}else{
if(is_numeric($update_id)){
$data = $this->get_data_from_db($update_id);
}
}
if(!isset($data)){
$data = $this->get_data_from_post();
}
//$titles = array();
$query = $this->get('title');
foreach($query->result() as $row){
$titles[] = $row->title;
}
$data['titles'] = $titles;
$data['update_id'] = $update_id;
$data['view_file'] = "create";
$this->load->module('templates');
$this->templates->admin_template($data);
}
function submit()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'required|xss_clean');
if($this->form_validation->run($this) == FALSE){
$this->create();
}else{
$data = $this->get_data_from_post();
$update_id = $this->uri->segment(3);
if(is_numeric($update_id)){
$this->_update($update_id, $data);
}else{
$this->_insert($data);
}
redirect('menus/manage');
}
}
create.php view
<div class="row">
<div class="col-md-12">
<h2>Create Menus</h2>
<h5>Welcome Jhon Deo , Need to make dynamic. </h5>
</div>
</div>
<hr />
<?php
echo validation_errors("<p style='color: red;'>", "</p>");
echo form_open('menus/submit/'.$update_id);
?>
<div class="row">
<div class="col-md-12">
<form role="form">
<div class="form-group">
<select name="menus">
<?php
foreach($titles as $title){
echo "<option value=".$title.">".$title."</option>";
}
?>
</select>
</div>
<div class="form-group">
<label>Title</label>
<!-- <input class="form-control" /> -->
<?php
$data = array(
'name' => 'title',
'id' => 'title',
'value' => $title,
'class' => 'form-control',
);
echo form_input($data);
?>
</div>
<?php
$data = array(
'name' => 'submit',
'id' => 'submit',
'value' => 'Submit',
'class' => 'btn btn-success',
'style' => 'width: 100%',
);
echo form_submit($data);
?>
</form>
</div>
</div>
<?php
echo form_close();
?>
UPDATE:
this is what I have when I print_r($titles)
Array
(
[0] => About Us
[1] => Home
)
If there is anything you don't understand or if you need me to give more information please let me know.
You should have declared a model. From there, you can create a function that will save the values in the database that you initialize via controller. You should utilize the MVC pattern of it. CodeIgniter has a great documentation to read about what I am pointing out.. https://codeigniter.com/user_guide/overview/mvc.html?highlight=model

Resources