file upload error messages are not displaying in codeigniter - php

I'm trying to insert data into database through a form. I'm uploading 2 image files, in database path of the files will be stored. I'm trying to do server side validation. when user does not upload a file or when user is uploading wrong file type, an error messages should display and page should return to same page with no data inserted into database.
This is my view:
<div class="main-panel">
<div class="content-wrapper">
<div class="row">
<div class="col-md-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Add News & Event</h4>
<p class="card-description"> </p>
<?php echo validation_errors("<div class='alert alert-danger'>","</div>");?>
<?php if($failed = $this->session->flashdata('addNewsFailed')){
echo '<div class="alert alert-danger">' ;
echo $failed;
echo '</div>';
}?>
<form class="forms-sample" action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputName1">Title</label>
<input type="text" class="form-control" id="exampleInputName1" value="<?php echo
set_value("title");?>" name="title">
</div>
<div class="form-group">
<label for="exampleInputName1">Sub Title</label>
<input type="text" class="form-control" id="exampleInputName1" value="<?php echo set_value("sub");?>" name="sub_title">
</div>
<div class="form-group">
<label for="exampleInputName1">Event Date</label>
<input type="text" class="form-control" id="exampleInputName1" name="date" value="<?php echo date('d - M - y ');//echo set_value("date");?>">
</div>
<div class="container">
<div class="row">
<div class="col-md">
<div class="form-group">
<label>Feature Image</label>
<div class="input-group col-xs-12">
<input type="file" class="form-control file-upload-info" placeholder="Upload Image" name="img" style="z-index: 9999; opacity: 0;" id="image">
<div id="imageName"></div>
<span class="input-group-append">
<button class="file-upload-browse btn btn-info" type="button" style="position: absolute; left: 0; padding: 6px 23px;border-radius:3px;">Upload</button> </span>
</div>
<?php if(isset($upload_error)){
echo $upload_error;
}?>
</div>
</div>
<div class="col-md">
<div class="form-group">
<label> Banner Image</label>
<div class="input-group col-xs-12">
<input type="file" class="form-control file-upload-info" placeholder="Upload Image" name="banner" id="banner" style="opacity: 0; z-index: 9999;">
<div id="bannerName"></div>
<span class="input-group-append">
<button class="file-upload-browse btn btn-info" type="button" style="position: absolute;left: 0;padding: 6px 23px;border-radius: 3px;">Upload</button></span>
</div>
<?php if(isset($upload_error1)){
echo $upload_error1;
}?>
</div>
</div>
</div>
</div>
<span class="input-group-append">-->
<div class="form-group">
<label for="exampleTextarea1">Text</label>
<textarea class="form-control" id="exampleTextarea1" rows="2" name="para" value=""><?php echo set_value("para");?></textarea>
</div>
<button type="submit" class="btn btn-success mr-2">Add</button>
<button class="btn btn-light">Cancel</button>
</form>
</div>
</div>
</div>
</div>
</div>
This is my controller:
public function addEvent()
{
//load library
$this->load->library('form_validation');
$this->load->helper('form');
//set rules for validation
$this->form_validation->set_rules("title", "Title", "required");
$this->form_validation->set_rules("date", "Event Date", "required");
$this->form_validation->set_rules("para", "Text", "required");
//template
$this->output->set_template('admin_layout');
//image upload
$config = [
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png',
];
$this->load->library('upload', $config);
//validation
if ($this->form_validation->run()) {
$post = $this->input->post();
if (!$this->upload->do_upload('img')) {
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/pages/forms/addEvent', compact('upload_error'));
} else {
$Feature1 = $this->upload->data();
$image_path = base_url('uploads/' . $Feature1['raw_name'] . $Feature1['file_ext']);
$post['image_path'] = $image_path;
}
if (!$this->upload->do_upload('banner')) {
$upload_error1 = $this->upload->display_errors();
$this->load->view('dashboard/pages/forms/addEvent', compact('upload_error1'));
} else {
$carsousel = $this->upload->data();
$banner = base_url('uploads/' . $carsousel['raw_name'] . $carsousel['file_ext']);
$post['banner'] = $banner;
}
$this->load->model('loginmodel', 'addNews');
$insert_id = $this->addNews->addNews($post);
if ($insert_id) {
$this->session->set_flashdata("addNewsSuccess", 'News & Event Added Successfully');
redirect('dashboard/update_news/' . $insert_id);
} else {
$this->session->set_flashdata("addNewsFailed", 'Failed');
$this->load->view('dashboard/pages/forms/addEvent');
}
} else {
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/pages/forms/addEvent', compact('upload_error'));
}
}
This is my model:
public function addNews($array)
{
$this->db->insert('news', $array);
return $this->db->insert_id();
}
My form validation are working perfectly but when user is uploading wrong file type or does not upload any file then file upload error message is not displaying and data is inserting into database the with both image field empty.

Related

Error when input date on laravel 5.4

I am using Laravel to create a project but I get some issue when creating a form that uses date:
Is there something missing in the table or script?
Here the table
Here the controller
public function index(Request $request){
$data = array();
if($request->isMethod('post') == "post"){
$pendaftar = new PendaftarModel();
$pendaftar->tgl =$request->input(['date']);
$pendaftar->nopol =$request->input('no polisi');
$pendaftar->motor =$request->input('jenis service');
$pendaftar->servis =$request->input('keluhan kendaraan');
$pendaftar->keluhan =$request->input('keluhan kendaraan');
// $pendaftar->keluhan =$request->input('keluhan kendaraan');
if($pendaftar->save()){
$data["status"] = "success";
$data["message"] = "Selamat, booking berhasil. Staff kami akan segera menghubungi anda untuk penjadwalan";
}else {
$data["status"] = "danger";
$data["message"] = "Maaf, Booking Gagal";
}
}
return view("daftar", $data);
The view blade
div class="well well-lg">
<div class="container">
<h2>Booking Online</h2>
<span>Halaman untuk melakukan pendaftaran kendaraan.</span>
</div>
</div>
<div class="container">
<div class="alert alert-info">
<i class="glyphicon glyphicon-info-sign"></i> Silahkan isi data berikut
</div>
<div class="panel panel-primary">
<div class="panel-heading">
Form Data Kendaraan
</div>
<div class="panel-body">
#if(isset($status))
<div class="alert alert-<?php echo $status; ?>">
<?php echo $message; ?>
</div>
#endif
<form method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="tanggal">Pilih Tanggal</label>
<input class="form-control" id="tanggal" required type="date" name="tgl" max="3000-12-31"
min="1000-01-01" placeholder="Pilih Tanggal">
</div>
<div class="form-group">
<label for="nopol">Nomor Polisi:</label>
<input class="form-control" id="nopol" required type="text" name="nopol" placeholder="Masukkan No Polisi">
</div>
<div class="form-group">
<label for="motor">Jenis Motor:</label>
<input class="form-control" id="motor" required type="text" name="motor" placeholder="Matic/Bebek/Sport">
</div>
<div class="form-group">
<label for="servis">Tipe Service:</label>
<input class="form-control" id="servis" required type="text" name="servis" placeholder="Besar/Kecils">
</div>
<div class="form-group">
<label for="keluhan">Keluhan Kendaraan:</label>
<textarea name="keluhan" id="keluhan" required class="form-control" rows="5" placeholder="Tulis Keluhan Motor Anda"></textarea>
</div>
<button type="submit" name="submit" class="btn btn-success btn-lg"><i class="glyphicon glyphicon-send"></i> Submit</button>
<button type="reset" class="btn btn-danger btn-lg">Reset</button>
</form>
</div>
</div>
</div>
The Model
{
//
protected $table = "pendaftar";
public $timestamps = true;
protected $fillable=['tgl','nopol','motor','servis','keluhan'];
}
In the snapshot, Your table is missing updated_at column, create a column with the name "updated_at" in your pendafter table.
Another way you can set the model like this:
{
//
protected $table = "pendaftar";
public $timestamps = false; //it should be false
protected $fillable=['tgl','nopol','motor','servis','keluhan'];
}

Dropzone sending all queue of uploaded files to the controller once

I am trying to send multiple files in one request using DropZone js.
<script type="text/javascript">
Dropzone.autoDiscover = false;
var file= new Dropzone(".dropzone",{
url: any url,
method:"post",
paramName:"PhotoFiles",
addRemoveLinks:true,
autoProcessQueue: false
});
//Upload file onsubmit
$('#UploadMultiFiles').submit(function(){
file.processQueue();
});
file.on("sending",function(a,b,c){
a.token=Math.random();
c.append("token",a.token);
});
The issue is I have other inputs in the same form that is why I used onsubmit, and these inputs are saved in a table and the images from dropzone are saved in another table with and both tables have one to many relationship
The Controller like:
public function university_offers($id){
$data['university_offer_name']=$this->input->post('university_offer_name');
$data['university_id_fk']=$this->input->post('university_id_fk');
$data['university_offer_details']=$this->input->post('university_offer_details');
if ($this->input->post('save')){
$data2['university_offer_id_fk'] = insertrecords('university_offers',$data);
$data2['university_id_fk'] = $data['university_id_fk'];
//when I put the next IF at the begining of the function it works but ofcourse without the other data fields that I need.
if(isset($_FILES) && $_FILES != null){
$data2['photo_name'] = upload_image('PhotoFiles');
insertrecords('university_offer_photos',$data2);
}
if (insertrecords('university_offer_photos',$data2)==true)
message('success','');
redirect('Admin/university_offers/0','refresh');
}
$data['view']="admin/universities/university_offers";
$this->load->view('index',$data);
}
What I need is sending al uploaded files and do a loop in the controller to save it right in the database, not sending each file to the controller and saving it.
Edit:
My view is like:
<form action="university_offers/<?=$id?>" id="UploadMultiFiles" autocomplete="off" method="post" enctype="multipart/form-data" class="m-t-5" novalidate>
<div class="form-body">
<h3 class="card-title">بيانات العرض</h3>
<hr>
<div class="row p-t-20">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">إسم العرض<span class="text-danger">*</span></label>
<div class="controls">
<input type="text" autocomplete="off" name="university_offer_name" class="form-control" required value="<?php if(isset($result)) echo $result['university_offer_name']?>" data-validation-required-message="يجب إدخال إسم العرض" placeholder="إسم العرض">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">إسم الجامعة<span class="text-danger">*</span></label>
<div class="controls">
<select name="university_id_fk" id="select" class="form-control" required data-validation-required-message="يجب إختيار الجامعة" aria-invalid="false">
<option value="">إختر الجامعة</option>
<?php
foreach (selectrecords("*",'universities') as $university):
$select = '';
if(isset($result) && $result['university_id_fk'] == $university->university_id_pk)
$select = 'selected';
?>
<option <?=$select?> value="<?php echo $university->university_id_pk ?>"><?php echo $university->university_name ?></option>
<?php endforeach;?>
</select>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label">تفاصيل العرض<span class="text-danger">*</span></label>
<div class="controls">
<textarea id="mymce" name="university_offer_details"><?php if(isset($result)) echo $result['university_offer_details'] ?></textarea>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label">صور العرض<span class="text-danger">*</span></label>
<div class="row">
<?php
if(isset($result)) {
foreach (selectrecords('*','university_offer_photos',array('university_offer_id_fk'=>$result['university_offer_id_pk'])) as $photo):
echo'
<div class="form-group text-center" id="'.$photo->photo_id_pk.'">
<div class="col-md-12">
<img style="border: none; height: 150px; width: 150px; border-radius: 10px;" class="img-thumbnail" src="'.base_url().'public/uploads/images/'.$photo->photo_name.'">
</div>
حذف الملف
</div>
';
endforeach;
}
?>
</div>
<div class="dropzone">
<div class="dz-message">
<span> Drag and Drop your files here Or Click here to upload</span>
</div>
</div>
</div>
</div>
</div>
<div class="form-actions">
<input type="hidden" id="url" value="university_offers/<?=$id?>" />
<?php
if($id == 0)
echo '<button type="submit" id="butt" name="save" value="save" class="btn btn-primary"> <i class="fa fa-check"></i> حفظ</button>';
else
echo '<button type="submit" id="butt" name="edit" value="edit" class="btn btn-primary"><i class="fa fa-check"></i> حفظ</button>';
?>
<button type="reset" class="btn btn-inverse"><i class="fa fa-times"></i> إلغاء</button>
<?php
if($id == 0)
echo'<button type="button" id="backword" class="btn btn-second"><i class="fa fa-undo"></i> رجوع</button>';
else{
echo '<input type="hidden" name="university_offer_id_pk" value="'.$result['university_offer_id_pk'].'"/>
<button type="button" class="btn btn-second"><i class="fa fa-undo"></i> رجوع</button>';
}
?>
</div>
</div>
</form>
upload_image function, I put it in the Helper
function upload_image($file_name){
$CI =& get_instance();
$config['upload_path'] = 'public/uploads/images';
$config['allowed_types'] = 'gif|Gif|ico|ICO|jpg|JPG|jpeg|JPEG|BNG|png|PNG|bmp|BMP|WMV|wmv|MP3|mp3|FLV|flv|SWF|swf';
$config['max_size'] = '1024*8';
$config['encrypt_name']=true;
$CI->load->library('upload',$config);
if(! $CI->upload->do_upload($file_name)){
return false;
}else{
$datafile = $CI->upload->data();
thumb($datafile);
watermark($datafile);
return $datafile['file_name'];
}}

How to upload a image in codeigniter

I am unable to upload a image in the destination folder in codeigniter, I created one controller under the controller/admin folder with a name called site. And I added one model under the model folder with a name called model_view, and finally I created one view in the view folder with a name called view_addsite. And I created one table in the mysql with a name called sitesettings and 14 columns are added in that table. Problem hear is all fields are added in the table except image. please find the code.
controller(site)::
===========
public function add()
{
$datte = date('Y-m-d H:i:s');
if(!$this->input->post('buttonSubmit'))
{
$data['message'] = '';
$this->load->view('admin/view_addsite', $data);
}
else
{
//$this->load->library('form_validation');
if($this->form_validation->run('addsite'))
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_width'] = '2048';
$config['max_height'] = '2048';
$this->load->library('upload', $config);
$title = $this->input->post('title');
$name = $this->input->post('name');
$admin = $this->input->post('admin');
$mail = $this->input->post('mail');
$phone = $this->input->post('phone');
$contact=$this->input->post('contact');
$fb=$this->input->post('fb');
$tw=$this->input->post('tw');
$yt=$this->input->post('yt');
$in=$this->input->post('in');
$gp=$this->input->post('gp');
$ft=$this->input->post('ft');
$this->upload->do_upload('image');
$data = $this->upload->data('image');
$image= $data['file_name'];
$this>model_site>
insert($title,$image,$name,$admin,$mail,
$phone,$contact,$fb,$tw,$yt,$in,$gp,$ft);
$this->session->set_flashdata('message','site Successfully
Created.');
redirect(base_url('admin/site'));
}
else
{
$data['message'] = validation_errors();
$this->load->view('admin/view_addsite', $data);
}
}
}
Model(model_site)::
===================
public function
insert($title,$image,$name,$admin,$mail,$phone,$contact,
$fb,$tw,$yt,$in,$gp,$ft)
{
$data = array(
'admintitle' => $title,
'logo' => $image,
'fromname' => $name,
'adminemail'=> $admin,
'receivemail' => $mail,
'phonenumber' => $phone,
'contactaddress' => $contact,
'facebook' => $fb,
'twitter'=>$tw,
'youtube' => $yt,
'instagram' => $in,
'googleplus' => $gp,
'footer' => $ft,
);
$this->db->insert('sitesettings', $data);
}
view(view_addsite)::
===================
<!-- page content -->
<div class="right_col" role="main">
<div class="">
<div class="page-title">
<div class="title_left">
<h3>Sitesettings</h3>
</div>
</div><div class="clearfix"></div>
<hr>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Add a new Site</h2>
<ul class="nav navbar-right panel_toolbox">
<li><a class="collapse-link"><i class="fa fa-
chevron-up"></i></a></li>
<li><a class="close-link"><i class="fa fa-close">
</i></a></li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<label><?php echo $message; ?></label>
<form method="post">
<fieldset>
<div class="form-group">
AdminPage Title : <input class="form-control"
placeholder="Admin Title" name="title" id="title"
type="text" ><span id="user-availability-status">
</span>
<div class="form-group">
Select image to upload:
<input type="file" name="fileToUpload"
id="fileToUpload">
</form>
<div class="form-group">
From Name : <input class="form-control"
placeholder="Form Title" name="name" id="name" type="text"
><span id="user-availability-status"></span>
<div class="form-group">
Admin Email Address : <input class="form-control"
placeholder="Admin Email" name="admin" id="admin"
type="text" onBlur="checkAvailability()" ><span
id="user-availability-status"></span>
<div class="form-group">
Receive Mail Address for Contact Us Form : <input
class="form-control" placeholder="Receive Email"
name="mail" id="mail" type="text"
onBlur="checkAvailability()" ><span id="user-availability-
status"></span>
</div>
<div class="form-group">
Phone number: <input class="form-control"
placeholder="Phone Number" name="phone" id="phone"
type="text" onBlur="checkAvailability()" ><span id="user-
availability-status"></span>
</div>
<div class="form-group">
Contact Adress : <input class="form-control"
placeholder="Contact Address" name="contact" id="contact"
type="text" onBlur="checkAvailability()" ><span
id="user-availability-status"></span>
</div>
<div class="form-group">
Facebook : <input class="form-control" placeholder="Facebook"
name="fb" id="fb" type="text" onBlur="checkAvailability()" >
<span id="user-availability-status"></span>
</div>
<div class="form-group">
Twitter : <input class="form-control" placeholder="Twitter"
name="tw" id="tw" type="text" onBlur="checkAvailability()" >
<span id="user-availability-status"></span>
</div>
<div class="form-group">
Youtube : <input class="form-control"
placeholder="Youtube" name="yt" id="yt" type="text"
onBlur="checkAvailability()" ><span id="user-availability-
status"></span>
</div>
<div class="form-group">
Instagram : <input class="form-control"
placeholder="Instagram" name="in" id="in" type="text"
onBlur="checkAvailability()" ><span id="user-availability-
status"></span>
</div>
<div class="form-group">
Google Plus: <input class="form-control"
placeholder="Google Plus" name="gp" id="gp" type="text"
onBlur="checkAvailability()" ><span id="user-availability-
status"></span>
</div>
<div class="form-group">
Footer: <input class="form-control"
placeholder="Footer" name="ft" id="ft"
type="text" onBlur="checkAvailability()" ><span id="user-
availability-status"></span>
</div>
<input type="submit" name="buttonSubmit"
value="add" class="btn btn-success" />
</fieldset>
</form>
</div> <!-- /content -->
</div><!-- /x-panel -->
</div> <!-- /col -->
</div> <!-- /row -->
</div>
</div> <!-- /.col-right -->
<!-- /page content -->
<?php $this->load->view('admin/partials/admin_footer'); ?>
<?php if($this->session->flashdata('message') != NULL) : ?>
<script>
swal({
title: "Success",
text: "<?php echo $this->session->flashdata('message'); ?>",
type: "success",
timer: 1500,
showConfirmButton: false
});
</script>
<?php endif ?>
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
for more detail see:upload file with codeigniter
You are missing
enctype="multipart/form-data"
on your form tag and also remove the </form> just after the image input box.
Controller:
$doc_1 = "uploads/img_1/";
if (isset($_FILES['userfile_1']) && !empty($_FILES['userfile_1'])) {
$filename = pathinfo($_FILES['userfile_1']['name']);
if (move_uploaded_file($_FILES['userfile_1']['tmp_name'], $doc_1.$filename['basename'])) {
$attch_1 = base_url().$doc_1.$filename['basename'];
}
else {
$attch_1 = "na";
}
}
view:
<?php echo form_open_multipart("store_property", ['class'=>'form-horizontal']); ?>
<input type="file" name="userfile_1" />

Unable to save multiple images in database Laravel 5

I have a table named "cases" where the column are id image1,content1,image2,content2,image3 and content3
My content1,content2,content3 will be saved in database when i submit it from form but images are nither saved in folder nor in database. I need help
Controller
public function store(Request $request,SidContainRequest $request)
{
$sidContain = new sidcontain;
$sidContain->content1 = $request->get('page_content1');
$sidContain->content2 = $request->get('page_content2');
$sidContain->content3 = $request->get('page_content3');
//upload multiple files
$files= [];
if($request->file('leftimage')) $files[] = $request->file('leftimage');
if($request->file('Middleimage')) $files[] = $request->fiel('Middleimage');
if($request->file('Rightimage')) $files[] = $request->file('Rightimage');
foreach($files as $flle)
{
if(!empty($file))
{
$filename[] = $file->getClientOrginalName();
if(isset($filename)){
$file->move(base_path().'/frontend/sidimage/',end($filename));
}
}
$sidContain->image1 = $filename[0];
$sidContain->image2 = $filename[1];
$sidContain->image3 = $filename[2];
}
$ok = $sidContain->save();
if($ok)
{
\Session::flash('flash_message','Report Added Successfully!');
return Redirect::to('administrator/sidConatin/create');
}
}
view/form
<div class="form-group">
<label>Left Image</label>
<input type="file" name="leftimage">
#if($errors->has('leftimage')) <p style="color:red;">{{$errors->first('leftimage')}}</p>#endif
</div>
<div class="form-group">
<label>Left Content</label>
<textarea name="page_content1" id="page_content1" class="editor form-control"></textarea>
#if($errors->has('page_content1'))<p style="color:red;">{{$errors->first('page_content1')}}</p>#endif
</div>
<div class="form-group">
<label>Middle Image</label>
<input type="file" name="Middleimage">
#if($errors->has('Middleimage')) <p style="color:red;">{{$errors->first('Middleimage')}}</p>#endif
</div>
<div class="form-group">
<label>Middle Content</label>
<textarea name="page_content2" id="page_content2" class="editor form-control"></textarea>
#if($errors->has('page_content2')) <p style="color:red;">{{$errors->first('page_content2')}}</p>#endif
</div>
<div class="form-group">
<label>Right Image</label>
<input type="file" name="Rightimage">
#if($errors->has('Rightimage')) <p style="color:red;">{{$errors->first('Rightimage')}}</p>#endif
</div>
<div class="form-group">
<label>Right Content</label>
<textarea name="page_content3" id="page_content3" class="editor form-control"></textarea>
#if($errors->has('page_content3')) <p style="color:red;">{{$errors->first('page_content3')}}</p>#endif
</div>
<div style="margin-top: 15px;">
<button type="submit" class="btn btn-danger">Submit</button>
</div>
</form>

Dependend DropDown using Codeigniter, No Jquery nor Ajax

I want to make subsector dependent on sector, i am not using jquery nor ajax
This is my Controller
<?php
/*
*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Salesforce extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->database();
$this->load->library('form_validation');
//load the employee model
$this->load->model('sf_model');
}
//index function
function index()
{
//...
$data['sector'] = $this->sf_model->get_sector();
$data['subsector'] = $this->sf_model->get_subsector();
$data['type'] = $this->sf_model->get_type();
//set validation rules
$this->form_validation->set_rules('a_name', 'Account Name', 'trim|required|xss_clean|callback_alpha_only_space');
$this->form_validation->set_rules('a_web', 'Website', 'trim|required|xss_clean');
$this->form_validation->set_rules('a_type', 'Type', 'callback_combo_check');
$this->form_validation->set_rules('a_sector', 'Sector', 'callback_combo_check');
$this->form_validation->set_rules('a_subsector', 'Sub Sector', 'callback_combo_check');
if ($this->form_validation->run() == FALSE)
{
//fail validation
//echo 'Validation failed';
//print_r($_REQUEST);
$this->load->view('sf_view', $data);
//
}
else
{
//pass validation
$data = array(
'a_name' => $this->input->post('a_name'),
'a_website' => $this->input->post('a_web'),
't_id' => $this->input->post('a_type'),
's_id' => $this->input->post('a_sector'),
'ss_id' => $this->input->post('a_subsector'),
'a_billingStreet' => $this->input->post('a_billingStreet'),
'a_billingState' => $this->input->post('a_billingState'),
'a_billingZip' => $this->input->post('a_billingZip'),
'a_billingCountry' => $this->input->post('a_billingCountry'),
'a_billingCity' => $this->input->post('a_billingCity'),
'a_phone' => $this->input->post('a_phone'),
'a_mobile' => $this->input->post('a_mobile'),
'a_fax' => $this->input->post('a_fax'),
);
//print_r($data);
//exit;
//insert the form data into database
$this->db->insert('account_info', $data);
//display success message
$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">New Account Created</div>');
redirect('salesforce/index');
}
}
//custom validation function for dropdown input
function combo_check($str)
{
if ($str == '-SELECT-')
{
$this->form_validation->set_message('combo_check', 'Valid %s Name is required');
return FALSE;
}
else
{
return TRUE;
}
}
//custom validation function to accept only alpha and space input
function alpha_only_space($str)
{
if (!preg_match("/^([-a-z ])+$/i", $str))
{
$this->form_validation->set_message('alpha_only_space', 'The %s field must contain only alphabets or spaces');
return FALSE;
}
else
{
return TRUE;
}
}
}
This is my Model
<?php
class Sf_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
function get_sector()
{
$results = $this->db->select('s_id, s_name')->from('account_sector')->get()->result();
$s_id = array('-SELECT-');
$s_name = array('-SELECT-');
for ($i = 0; $i < count($results); $i++)
{
array_push($s_id, $results[$i]->s_id);
array_push($s_name, $results[$i]->s_name);
}
return $sector_result = array_combine($s_id, $s_name);
}
function get_subsector()
{
$results = $this->db->select('ss_id, ss_name')->from('account_subsector')->get()->result();
$ss_id = array('-SELECT-');
$ss_name = array('-SELECT-');
for ($i = 0; $i < count($results); $i++)
{
array_push($ss_id, $results[$i]->ss_id);
array_push($ss_name, $results[$i]->ss_name);
}
return $subsector_result = array_combine($ss_id, $ss_name);
}
function get_type()
{
$results = $this->db->select('t_id, t_name')->from('account_type')->get()->result();
$t_id = array('-SELECT-');
$t_name = array('-SELECT-');
for ($i = 0; $i < count($results); $i++)
{
array_push($t_id, $results[$i]->t_id);
array_push($t_name, $results[$i]->t_name);
}
return $type_result = array_combine($t_id, $t_name);
}
}
>
This is my View
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SalesForce | Edit / New Account Details</title>
<!--link the bootstrap css file-->
<link href="<?php echo base_url("bt/css/bootstrap.css"); ?>" rel="stylesheet" type="text/css" />
<!-- link jquery ui css-->
<link href="<?php echo base_url('bt/css/jquery-ui.min.css'); ?>" rel="stylesheet" type="text/css" />
<!--include jquery library-->
<script src="<?php echo base_url('bt/js/jquery-1.11.3.js'); ?>"></script>
<!--load jquery ui js file-->
<script src="<?php echo base_url('bt/js/jquery-ui.min.js'); ?>"></script>
<style type="text/css">
.colbox {
margin-left: 0px;
margin-right: 0px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-offset-3 col-lg-6 col-sm-6 well">
<legend>Account Information</legend>
<?php
$attributes = array("class" => "form-horizontal", "id" => "accounts", "name" => "accounts");
echo form_open("salesforce", $attributes);?>
<fieldset>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="a_name" class="control-label">Account Name</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="a_name" name="a_name" placeholder="Enter Account Name" type="text" class="form-control" value="<?php echo set_value('a_name'); ?>" />
<span class="text-danger"><?php echo form_error('a_name'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="a_web" class="control-label">Website</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="a_web" name="a_web" placeholder="Enter Website" type="text" class="form-control" value="<?php echo set_value('a_web'); ?>" />
<span class="text-danger"><?php echo form_error('a_web'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="a_type" class="control-label">Type</label>
</div>
<div class="col-lg-8 col-sm-8">
<?php
$attributes = 'class = "form-control" id = "a_type"';
echo form_dropdown('a_type',$type,set_value('a_type'),$attributes);?>
<span class="text-danger"><?php echo form_error('a_type'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="a_sector" class="control-label">Sector</label>
</div>
<div class="col-lg-8 col-sm-8">
<?php
$attributes = 'class = "form-control" id = "a_sector"';
echo form_dropdown('a_sector',$sector,set_value('a_sector'),$attributes);?>
<span class="text-danger"><?php echo form_error('a_sector'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="a_subsector" class="control-label">Sub Sector</label>
</div>
<div class="col-lg-8 col-sm-8">
<?php
$attributes = 'class = "form-control" id = "a_subsector"';
echo form_dropdown('a_subsector',$subsector, set_value('a_subsector'), $attributes);?>
<span class="text-danger"><?php echo form_error('a_subsector'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="a_billingStreet" class="control-label">Billing Street</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="a_billingStreet" name="a_billingStreet" placeholder="Enter Billing Street" type="text" class="form-control" value="<?php echo set_value('a_billingStreet'); ?>" />
<span class="text-danger"><?php echo form_error('a_billingStreet'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="a_billingState" class="control-label">B-State/Province</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="a_billingState" name="a_billingState" placeholder="Enter State/Province" type="text" class="form-control" value="<?php echo set_value('a_billingState'); ?>" />
<span class="text-danger"><?php echo form_error('a_billingState'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="a_billingZip" class="control-label">B-Zip/Postal</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="a_billingZip" name="a_billingZip" placeholder="Enter Zip/Postal" type="text" class="form-control" value="<?php echo set_value('a_billingZip'); ?>" />
<span class="text-danger"><?php echo form_error('a_billingZip'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="a_billingCountry" class="control-label">Billing Country</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="a_billingCountry" name="a_billingCountry" placeholder="Enter Billing Country" type="text" class="form-control" value="<?php echo set_value('a_billingCountry'); ?>" />
<span class="text-danger"><?php echo form_error('a_billingCountry'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="a_billingCity" class="control-label">Billing City</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="a_billingCity" name="a_billingCity" placeholder="Enter Billing City" type="text" class="form-control" value="<?php echo set_value('a_billingCity'); ?>" />
<span class="text-danger"><?php echo form_error('a_billingCity'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="a_phone" class="control-label">Phone</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="a_phone" name="a_phone" placeholder="Enter Phone Number" type="text" class="form-control" value="<?php echo set_value('a_phone'); ?>" />
<span class="text-danger"><?php echo form_error('a_phone'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="a_mobile" class="control-label">Mobile Number</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="a_mobile" name="a_mobile" placeholder="Enter Mobile Number" type="text" class="form-control" value="<?php echo set_value('a_mobile'); ?>" />
<span class="text-danger"><?php echo form_error('a_mobile'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="a_fax" class="control-label">Fax Number</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="a_fax" name="a_fax" placeholder="Enter Fax Number" type="text" class="form-control" value="<?php echo set_value('a_fax'); ?>" />
<span class="text-danger"><?php echo form_error('a_fax'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-lg-8 col-sm-8 text-left">
<input id="btn_add" name="btn_add" type="submit" class="btn btn-primary" value="Insert" />
<input id="btn_cancel" name="btn_cancel" type="reset" class="btn btn-danger" value="Cancel" />
</div>
</div>
</fieldset>
<?php echo form_close(); ?>
<?php echo $this->session->flashdata('msg'); ?>
</div>
</div>
</div>
</body>
</html>
Controller
$data['sector'] = $this->sf_model->get_sector();
if(isset($data['sector'])&&$data['sector']!="")
$data['subsector'] = $this->sf_model->get_subsector($data['sector']);
Model, In model pass sector as parameter to get_subsector function and then during database select please pass it to where or as per your requirement you may procced.
Also Please avoid array_push() function in loops, use $ss_id[] = $results[$i]->ss_id; because it is much faster.
function get_subsector($sector)
{
$results = $this->db->select('ss_id, ss_name')->from('account_subsector')->get()->where($sector)->result();
$ss_id = array('-SELECT-');
$ss_name = array('-SELECT-');
for ($i = 0; $i < count($results); $i++)
{
array_push($ss_id, $results[$i]->ss_id);
array_push($ss_name, $results[$i]->ss_name);
}
return $subsector_result = array_combine($ss_id, $ss_name);
}
using some js and ajax
<script>
$(document).ready(function(){
$('#a_subsector').attr('disabled','disabled');
$('#a_sector').change(function(){
$.ajax({
url:'/salesforce/fill_ss',
type:'post',
data: {sector:$('#a_sector').val()},
success:function(result){
$('#a_subsector').removeAttr('disabled');
//$('#a_subsector').(result);
document.getElementById('a_subsector').innerHTML=result;
}
});
});
});
</script>
Adding a Function to controller
function fill_ss()
{
$this->sf_model->get_subsector();
$sector = $_POST['sector'];
$data = $this->sf_model->matching($sector);
//print_r($data);
for ($i = 0; $i < count($data); $i++)
{
echo '<option value="'.$data[$i]->ss_id.'">'.$data[$i]->ss_name.'</option>';
//echo '<option value="'.$data[$i]->ss_id.'"></option>';
//array_push($t_id, $data[$i]->t_id);
//array_push($t_name, $data[$i]->t_name);
}
}
Model
function view_accounts()
{
$results = $this->db->select('a_name,t_id,a_website,a_billingStreet,a_billingZip,a_billingCountry,a_billingCity,a_phone,a_mobile')->from('account_info')->get()->result();
return $results;
}
function matching($match)
{
$results =$this->db->select('ss_id,ss_name')->from('account_subsector')->where('s_id',$match)->get()->result();
return $results;
}

Categories