what im trying to do is Im trying to upload an image to database but I dont know what is the reason why I've got an error like
Message: Undefined index: userfile
Message: Undefined variable: images
in my view. as you can see the name of the input file set as an array same as other tutorial
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Person Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input name="firstName" placeholder="First Name" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Image</label>
<div class="col-md-9">
<input type="file" name="userfile[]" id="file" class="form-control">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select name="gender" class="form-control">
<option value="">--Select Gender--</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Address</label>
<div class="col-md-9">
<textarea name="address" placeholder="Address" class="form-control"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input name="dob" placeholder="yyyy-mm-dd" class="form-control datepicker" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal
in my controller.
public function image()
{
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']); //this is line that has an error, the Message: Undefined index: userfile
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
}
$fileName = implode(',',$images); // the line that has an error, Message: Undefined variable: images
return $fileName;
}
public function ajax_add()
{
$this->_validate();
$data = array(
'firstName' => $this->input->post('firstName'),
//'lastName' => $this->input->post('lastName'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
'image' => $this->input->post($this->image()),
);
$insert = $this->person->save($data);
echo json_encode(array("status" => TRUE));
}
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = './upload/'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
public function ajax_update()
{
$this->_validate();
$data = array(
'firstName' => $this->input->post('firstName'),
// 'lastName' => $this->input->post('lastName'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
);
$this->person->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
I want to insert that image name to my database but that errors block me to do that... need help.
In your Ajax Request Please add
$("#form").submit(function(e){
e.preventDefault();
var fd = new FormData();
$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
return xhrobj;
},
data: formData,
So on....
//ajax close
});
And DOnt Forgot to use
enctype="multipart/form-data"
On form tag...And You will be fine
For Undefined variable: images
Please put
$images = array();// just before for loop.
$cpt = count($_FILES['userfile']);
Related
In Livewire component i have a form inside the modal to edit the information.
When I click on the button, the modal will open and display the item information inside the inputs.
The problem is that if one or all of the inputs do not change their value and the edit button is clicked, it gives the following error that says the values are empty!!. And the inputs must be changed so that there are no errors
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'network' cannot be null (SQL: update `networks` set `network` = ?, `networkName` = ?, `address` = ?, `address_regex` = ?, `tag_memo` = ?, `tag_regex` = ?, `min_withdraw` = ?, `max_withdraw` = ?, `fee` = ?, `deposit` = inactive, `withdraw` = inactive, `networks`.`updated_at` = 2021-06-09 10:18:52 where `id` = 8)
component code:
<?php
namespace App\Http\Livewire\Backend\Currency;
use App\Models\Network;
use Livewire\Component;
class Networks extends Component
{
protected $listeners = ['refreshNetwork' => '$refresh'];
public $confirming;
public $editId;
public $networkEdit;
public $networkNameEdit;
public $address_networkEdit;
public $address_regexEdit;
public $tag_memo_networkEdit;
public $tag_regexEdit;
public $min_withdrawEdit;
public $max_withdrawEdit;
public $feeEdit;
public $depositEdit = false;
public $withdrawEdit = false;
public function editForm($id,$action)
{
if ($network = Network::where('id' , $id)->first()) {
$this->editId = $id;
$this->dispatchBrowserEvent('editNetworkModal', $networkData = [
'network' => $network->network,
'networkName' => $network->networkName,
'address_network' => $network->address,
'address_regex' => $network->address_regex,
'tag_memo_network' => $network->tag_memo_network,
'tag_memo_regex' => $network->tag_memo_regex,
'min_withdraw' => $network->min_withdraw,
'max_withdraw' => $network->max_withdraw,
'fee' => $network->fee ,
'deposit' => $network->deposit,
'withdraw' => $network->withdraw,
]);
}else{
$this->alert('warning', 'شبکه مورد نظر پیدا نشد !', [
'position' => 'center',
'timer' => 2000,
'toast' => false,
'text' => '',
'confirmButtonText' => 'خب',
'cancelButtonText' => 'خب',
'showCancelButton' => false,
'showConfirmButton' => false,
]);
}
}
public function Update($action)
{
if ($action == 'edit')
{
Network::where('id' , $this->editId)->update([
'network' => $this->networkEdit,
'networkName' => $this->networkNameEdit,
'address' => $this->address_networkEdit,
'address_regex' => $this->address_regexEdit,
'tag_memo' => $this->tag_memo_networkEdit,
'tag_regex' => $this->tag_regexEdit,
'min_withdraw' => $this->min_withdrawEdit,
'max_withdraw' => $this->max_withdrawEdit,
'fee' => $this->feeEdit,
'deposit' => $this->depositEdit == false ? 'inactive' : 'active',
'withdraw' => $this->withdrawEdit== false ? 'inactive' : 'active',
]);
$this->emit('refreshNetwork');
$this->dispatchBrowserEvent('hideEditNetworkModal');
$this->alert('success', 'شبکه با موفقیت ویرایش شد.', [
'position' => 'center',
'timer' => 2000,
'toast' => false,
'text' => '',
'confirmButtonText' => 'خب',
'cancelButtonText' => 'خب',
'showCancelButton' => false,
'showConfirmButton' => false,
]);
}
}
public function render()
{
return view('livewire.backend.currency.networks');
}
}
modal:
<div wire:key="B" class="modal fade" tabindex="-1" id="editNetworkModal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">ویرایـش شبکـه انتقال</h5>
<a href="#" class="close" data-dismiss="modal" aria-label="Close">
<em class="icon ni ni-cross"></em>
</a>
</div>
<div class="modal-body">
<form action="#" class="form-validate is-alter">
<div class="row gy-3">
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="full-name">شبکه ارز</label>
<div class="form-control-wrap">
<input wire:model.defer="networkEdit" type="text" class="form-control" placeholder="مثال : BNB" id="networkEdit" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="email-address">نام شبکه</label>
<div class="form-control-wrap">
<input wire:model="networkNameEdit" id="networkNameEdit" type="text" class="form-control" placeholder="مثال: BEP20" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">ادرس</label>
<div class="form-control-wrap">
<input wire:model="address_networkEdit" type="text" class="form-control" id="address_networkEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">اعتبار سنجی آدرس شبکه به وسیله عبارات منظم</label>
<div class="form-control-wrap">
<input wire:model="address_regexEdit" type="text" class="form-control" id="address_regexEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">آدرس Memo یا Tag</label>
<div class="form-control-wrap">
<input wire:model="tag_memo_networkEdit" type="text" class="form-control" id="tag_memo_networkEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">اعتبار سنجی Memo شبکه به وسیله عبارات منظم</label>
<div class="form-control-wrap">
<input wire:model="tag_regexEdit" type="text" class="form-control" id="tag_regexEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">حداقل برداشت</label>
<div class="form-control-wrap">
<input wire:model="min_withdrawEdit" type="text" class="form-control" id="min_withdrawEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">حداکثر برداشت</label>
<div class="form-control-wrap">
<input wire:model="max_withdrawEdit" type="text" class="form-control" id="max_withdrawEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">کارمزد برداشت</label>
<div class="form-control-wrap">
<input wire:model="feeEdit" type="text" class="form-control" id="feeEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="custom-control custom-switch">
<input wire:model="depositEdit" type="checkbox" class="custom-control-input" id="depositEdit">
<label class="custom-control-label" for="deposit">واریـز به این آدرس</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="custom-control custom-switch">
<input wire:model.defer="withdrawEdit" type="checkbox" class="custom-control-input" id="withdrawEdit">
<label class="custom-control-label" for="withdraw">برداشت به این آدرس</label>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer bg-light">
<button wire:click="Update('edit')" class="btn btn-round btn-outline-primary ">
<div wire:loading wire:target="Update">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
</div>
<span class="w-100px">ویرایـش شبکـه</span>
</button>
<button data-dismiss="modal" aria-label="Close" class="btn btn-round btn-outline-secondary w-90px"><span>بستن</span></button>
</div>
</div>
</div>
</div>
and js code to set value for inputs and open modal:
window.addEventListener('editNetworkModal', event => {
$("#editNetworkModal").modal('show');
$('#networkEdit').val(event.detail.network);
$('#networkNameEdit').val(event.detail.networkName);
$('#address_networkEdit').val(event.detail.address_network);
$('#address_regexEdit').val(event.detail.address_regex);
$('#tag_memo_networkEdit').val(event.detail.tag_memo_network);
$('#tag_regexEdit').val(event.detail.tag_regex);
$('#min_withdrawEdit').val(event.detail.min_withdraw);
$('#max_withdrawEdit').val(event.detail.max_withdraw);
$('#feeEdit').val(event.detail.fee);
$('#depositEdit').val(event.detail.deposit);
$('#withdraw').val(event.detail.withdraw);
console.log(event.detail)
});
$this->dispatchBrowserEvent('editNetworkModal', $networkData = [
'network' => $network->network,
One of the goals of Livewire, is forget about JS for this kind of things. Binding the property with wire:model you don't need at all use JS, even pass this db information through the event. With a simple method that retrieve the data from db and assign it to the public properties is enough for you get this in frontend
public function editForm($id,$action)
{
$this->getModelData($id);
$this->dispatchBrowserEvent('openEditModal');
}
public function getModelData($modelId)
{
$model = Model::find($modelId);
$this->property1 = $model->property1;
//......
}
Here is the code for controller:
public function save_product(Request $request){
$request->validate([
'product_name' => 'required',
'product_price' => 'required',
'product_category' => 'required',
'description' => 'nullable',
'image1' => 'required',
'image2' => 'nullable',
'image3' => 'nullable',
], [
'product_name.required' => 'Product name field required',
'product_price.required' => 'Asking price field required',
'product_category.required' => 'Product category field required',
'image1.required' => 'You need a upload image-1 field',
]);
if($request->hasFile('image1') || $request->hasFile('image2') || $request->hasFile('image3')){
$file1 = $request->file('image1');
$file2 = $request->file('image2');
$file3 = $request->file('image3');
$text1 = $file1->getClientOriginalExtension();
$text2 = $file2->getClientOriginalExtension();
$text3 = $file3->getClientOriginalExtension();
$fileName1 = time().'.'.$text1;
$fileName2 = time().'.'.$text2;
$fileName3 = time().'.'.$text3;
$file1->move('uploads/product_image', $fileName1);
$file2->move('uploads/product_image', $fileName2);
$file3->move('uploads/product_image', $fileName3);
$product = Product::create([
'image1'=>$fileName1,
'image2'=>$fileName2,
'image3'=>$fileName3,
'product_category' => trim($request->input('product_category')),
'product_name' => trim($request->input('product_name')),
'product_price' => trim($request->input('product_price')),
'description' => trim($request->input('description')),
]);
}
return redirect()->route('add_product')
->with('success','Successfully added Product!');
}
Here is the code for blade template:
#extends('admin.layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
#include('pages.partials.flash_message')
</div>
</div>
</div>
<div class="card card-default">
<div class="card-header card-header-border-bottom">
<h2>Add Product</h2>
</div>
<div class="card-body">
<form action="{{route('save_product')}}" method="POST">
#csrf
<div class="form-group">
<label for="exampleFormControlSelect12">Select Category</label>
<input type="text" class="form-control" placeholder="Enter Arrival Time"
id="exampleFormControlSelect12" name="product_category" list="product_category"
autocomplete="off">
<datalist class="form-control" id="product_category" style="display: none" >
<option value="Women Clothes"></option>
<option value="Jewellery"></option>
<option value="Shoes"></option>
<option value="Sun Glass"></option>
<option value="Hair Band"></option>
</datalist>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-1</label>
</div>
#if ($errors->has('image1'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image1') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image1" class="custom-file-input" id="inputGroupFile01"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-2</label>
<small>*Optional</small>
</div>
#if ($errors->has('image2'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image2') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image2" class="custom-file-input" id="inputGroupFile02"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-3</label>
<small>*Optional</small>
</div>
#if ($errors->has('image3'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image3') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image3" class="custom-file-input" id="inputGroupFile03"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Product Name or Title</label>
<input type="text" name="product_name" class="form-control"
id="exampleFormControlInput1" placeholder="Enter Product Name or Title">
#if ($errors->has('product_name'))
<span class="text-danger" style="font-weight: bold">{{ $errors-
>first('product_name') }}</span>
#endif
</div>
<div class="form-group">
<label for="exampleFormControlInput2">Asking Price</label>
<input type="number" name="product_price" class="form-control"
id="exampleFormControlInput2" placeholder="Enter Asking Price">
#if ($errors->has('product_price'))
<span class="text-danger" style="font-weight: bold">{{ $errors-
>first('product_price') }}</span>
#endif
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Product Description</label>
<textarea class="form-control" name="product_description"
id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<div class="form-footer pt-4 pt-5 mt-4 border-top">
<button type="submit" class="btn btn-primary btn-default">Submit</button>
</div>
</form>
</div>
</div>
#endsection
Route:
Route::post('/admin/add_product','App\Http\Controllers\Admin\AdminController#save_product')
->name('save_product')->middleware('admin');
Model:
protected $fillable = [
'product_name',
'product_category',
'product_price',
'description',
'image1',
'image2',
'image3',
];
Migration:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->string('product_category');
$table->string('product_price');
$table->text('description')->nullable();
$table->string('image1');
$table->string('image2')->nullable();
$table->string('image3')->nullable();
$table->timestamps();
});
}
I can't find any error in my code please help me to find out. Thanks in advance.
You have to make separate if conditions for each image. Try this:
$fileName1='';
$fileName2='';
$fileName3='';
if($request->hasFile('image1')) {
$file1 = $request->file('image1');
$text1 = $file1->getClientOriginalExtension();
$fileName1 = time() . '.' . $text1;
$file1->move('uploads/product_image', $fileName1);
}
if($request->hasFile('image2')) {
$file2 = $request->file('image2');
$text2 = $file2->getClientOriginalExtension();
$fileName2 = time() . '.' . $text2;
$file2->move('uploads/product_image', $fileName2);
}
if($request->hasFile('image3')) {
$file3 = $request->file('image3');
$text3 = $file3->getClientOriginalExtension();
$fileName3 = time() . '.' . $text3;
$file3->move('uploads/product_image', $fileName3);
}
$product = Product::create([
'image1'=>$fileName1,
'image2'=>$fileName2,
'image3'=>$fileName3,
'product_category' => trim($request->input('product_category')),
'product_name' => trim($request->input('product_name')),
'product_price' => trim($request->input('product_price')),
'description' => trim($request->input('description')),
]);
if($product){
return redirect()->route('add_product')->with('success','Successfully added Product!');
}
else{
return redirect()->back()->with('error','Error!');
}
using enctype="multipart/form-data" inside form tag .
I have an AJAX request to add form fields in a database, but got issues while appending the new entry in my select list.
Here's the HTML
<select id="jform_proprietaire" name="jform[proprietaire]">
<option value="8">Hello World</option>
<option value="35">Jon Jon</option>
<option value="9">Jack Jonhson</option>
</select>
The Form in modal :
<div id="myModal" class="modal hide fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" style="display: block;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Ajouter un proprietaire</h3>
</div>
<div class="modal-body">
<form method="post" name="adminForm" id="propritaire-form">
<fieldset class="adminform">
<div class="resultats"></div>
<div class="control-group">
<div class="control-label"><label id="nom-lbl" for="nom" aria-invalid="false">
Nom</label>
</div>
<div class="controls"><input type="text" name="nom" id="nom" value=""></div>
</div>
<div class="control-group">
<div class="control-label"><label id="prenom-lbl" for="prenom" aria-invalid="false">
Prénom</label>
</div>
<div class="controls"><input type="text" name="prenom" id="prenom" value=""></div>
</div>
<div class="control-group">
<div class="control-label"><label id="societe-lbl" for="societe" aria-invalid="false">
Société</label>
</div>
<div class="controls"><input type="text" name="societe" id="societe" value=""></div>
<div class="control-group">
<div class="control-label"><label id="email-lbl" for="email" aria-invalid="false">
Email</label>
</div>
<div class="controls"><input type="email" name="email" class="validate-email" id="email" value=""></div>
</div>
</fieldset>
<input type="hidden" name="6f179ffa2a28133151f3cfe1553978e3" value="1">
</form>
</div>
<div class="modal-footer">
<a id="enregistrerproprio" class="btn btn-primary">Enregistrer</a>
</div>
</div>
And the script :
jQuery(document).ready(function(){
jQuery('#myModal').on('shown', function () {
jQuery('#enregistrerproprio').click(function(){
form=jQuery('#propritaire-form')
jQuery('#propritaire-form .resultats').html('<div class=\"progress progress-striped\"><div class=\"bar\" style=\"width: 30%;\"></div></div>');
jQuery.ajax({
type: 'POST',
url: 'index.php?option=com_visites&task=ajax.ajouteProprietaire&format=raw',
data: form.serializeArray(),
dataType: 'json',
success: function(data) {
jQuery('#propritaire-form .resultats').empty();
if(data.succes==1){
jQuery('#myModal').modal('hide');
jQuery('#jform_proprietaire').append('<option selected=\"true\" value=\"'+data.proprietaire.id+'\">'+data.proprietaire.nom+' '+data.proprietaire.prenom+'</option>');
} else {
jQuery('#propritaire-form .resultats').html('<div class=\"alert alert-error\"></div>');
for (i=0;i<data.retour.length;i++){
jQuery('#propritaire-form .resultats .alert').append('<p>'+data.retour[i].message+'</p>')
}
}
}
});
})
})
})
My data is well imported to the database but I have in console :
Uncaught TypeError: Cannot read property 'id' of null
at Object.success (index.php?option=com_jea&view=property&layout=edit&id=344:60)
at i (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:2)
at Object.fireWith [as resolveWith] (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:2)
at y (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:4)
at XMLHttpRequest.c (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:4)
For this line :
jQuery('#jform_proprietaire').append('<option selected=\"true\" value=\"'+data.proprietaire.id+'\">'+data.proprietaire.nom+' '+data.proprietaire.prenom+'</option>');
If someone could help would be great!!
Thanks in advance !
PS : I ommited to show the php ajouteproprietairefunction :
class VisitesControllerAjax extends JControllerAdmin
{
public function ajouteProprietaire(){
require_once JPATH_ADMINISTRATOR.'/components/com_visites/models/propritaire.php';
$input = JFactory::getApplication()->input;
$data=$input->getArray(array('nom' => '', 'prenom' => '', 'societe' => '','email' => '', 'telephone' => '', 'mobile' => '','adresse' => '', 'codepostal' => '', 'ville' => '', 'notes' => ''));
$data["state"]=1;
$model=new VisitesModelPropritaire();
$reussite=$model->save($data);
if ($reussite) {
$db= JFactory::getDbo();
$query=$db->getQuery(true);
$query->select('*')
->from('#__visites_proprio')
->where('id='.$db->insertid());
$db->setQuery($query);
$proprietaire=$db->loadObject();
echo json_encode(array('succes'=>1, 'proprietaire'=>$proprietaire));
} else {
echo json_encode(array('succes'=>0, 'retour'=>JFactory::getApplication()->getMessageQueue()));
}
}
}
Ok found the solution....
In the latest version of MySql the Last Insert ID isn't working very well.
So I changed my function to check on the email field since It's Unique for each user, Here's the updated code :
if ($reussite) {
$db= JFactory::getDbo();
$query=$db->getQuery(true);
$query->select('*');
$query->from('#__visites_proprio');
$query->where('email = \''.$data['email'].'\'');
$db->setQuery($query);
$proprietaire=$db->loadObject();
echo json_encode(array('succes'=>1, 'proprietaire'=>$proprietaire));
} else {
echo json_encode(array('succes'=>0, 'retour'=>JFactory::getApplication()->getMessageQueue()));
}
plaese help me dear,
I have a form where i want to upload files with multiple inputs(employee_name,resume,offer_letter,joining_letter)
using codeigniter.
My form looks like:
<form class="form-horizontal form-bordered" action="<?php echo base_url('save_employee/');?>" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label for="exampleInputEmail1">Employee Image</label>
<input type="file" class="form-control" name="employee_name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Resume/CV</label>
<input type="file" class="form-control" name="resume">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Offer letter</label>
<input type="file" class="form-control" name="offer_letter">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Joining Letter</label>
<input type="file" class="form-control" name="joining_letter">
</div>
</form
Put This In Your Controller Here Taking Four fields To Upload The Files
public function Add() {
$data = array();
$config = array(
'upload_path' => 'upload',
'allowed_types' => 'gif|jpg|png',
'max_size' => 250,
'max_width' => 1920,
'max_heigh' => 1080,
);
$this->load->library('upload', $config);
if($this->input->post('Submit')) {
$file_data = $this->upload->data();
$data['cnic_img'] = $file_data['file_name'];
$file_data = $this->upload->data();
$data['domcie_img'] = $file_data['file_name'];
$file_data = $this->upload->data();
$data['profile_img'] = $file_data['file_name'];
$file_data = $this->upload->data();
$data['report_img'] = $file_data['file_name'];
$lat_id = $this->your_model->save($data);
}
$this->load->View('your_template');
}
Put This In You Model
function save($data){
$this->db->insert('your_table', $data);
return $this->db->insert_id();
}
Here Is Your View
<div class="portlet-body form">
<!-- BEGIN FORM-->
<?php echo $this->upload->display_errors(''); ?>
<form class="form-horizontal" action="" <?php echo form_open_multipart();?>
<div class="form-group">
<label for="CNIC Image" class="col-md-3 control-label">CNIC Image:</label>
<div class="col-md-9">
<input type="file" id="cnic_img" name="cnic_img">
<p class="help-block">
Upload CNIC image Here.
</p>
</div>
</div>
</div>
</div>
<div class="portlet-body form">
<div class="form-body">
<div class="form-group">
<label for="Domicile Image" class="col-md-3 control-label">Domicile Image:</label>
<div class="col-md-9">
<input type="file" id="domcie_img" name="domcie_img">
<p class="help-block">
Upload Domicile Image Here.
</p>
</div>
</div>
</div>
</div>
<div class="portlet-body form">
<div class="form-body">
<div class="form-group">
<label for="Domicile Image" class="col-md-3 control-label">Profile Image:</label>
<div class="col-md-9">
<input type="file" id="profile_img" name="profile_img" >
<p class="help-block">
Upload Profile Image Here.
</p>
</div>
</div>
</div>
</div>
<div class="portlet-body form">
<div class="form-body">
<div class="form-group">
<label for="Domicile Image" class="col-md-3 control-label">Police validation Report:</label>
<div class="col-md-9">
<input type="file" id="report_img" name="report_img">
<p class="help-block">
Upload Police Validation Report Here.
</p>
</div>
</div>
</div>
</div>
This example is helped for some peoples.
$file = $_FILES;
$config['upload_path'] = './images/product/';
$config['allowed_types'] = 'jpg|jpeg';
$config['max_size'] = 2000;
$config['max_width'] = 1500;
$config['max_height'] = 1500;
$config['encrypt_name'] = TRUE;
if (empty($file['product_image']['name'])) {
$this->form_validation->set_rules('product_image', 'Product image', 'required');
} else {
// Load and initialize upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('product_image')){
$fileData = $this->upload->data();
} else {
$web['error']['product_image'] = $this->upload->display_errors();
$this->load->view('web_template',$web);
}
}
if (empty($file['customer_image']['name'])) {
$this->form_validation->set_rules('customer_image', 'Customer image', 'required');
} else {
// Load and initialize upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('customer_image')){
$cusfileData = $this->upload->data();
} else {
$web['error']['customer_image'] = $this->upload->display_errors();
$this->load->view('web_template',$web);
}
}
Get the image file name to insert data
$data = array(
'product_image' => $fileData['file_name'],
'customer_image' => $cusfileData['file_name']
);
This is not a how to upload image question . I have almost successfully managed to add a image upload function into my add client function . It works well when i try to upload a valid file .. but when i select a invalid file or larger file then it shows undefined variable upload_data and codeigniter database error where img_path is NULL it says Column 'img_path' cannot be null. why this function isn't working $this->upload->display_errors(); . The validation errors are showing nicely but no file validation error showing up.
I am using Codeigniter and hmvc
here is my controller
<?php
class Clients extends MX_Controller{
function __construct(){
parent::__construct();
$this->load->model('mdl_clients');
}
function add(){
$data['success'] = null;
$data['errors']= null;
if($_POST){
$config_arr = array(
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png',
'max_size' => '2048',
'max_width' => '1024',
'max_height' => '768',
'encrypt_name' => true,
);
$this->load->library('upload', $config_arr);
if (!$this->upload->do_upload()) {
$data['errors'] = $this->upload->display_errors(); // this isn't working
} else {
$upload_data = $this->upload->data();
}
$config=array(
array(
'field'=>'firstName',
'label'=>'First Name',
'rules'=>'required|max_length[15]|min_length[3]'
),
array(
'field'=>'city',
'label'=>'City',
'rules'=>'required'
),
array(
'field'=>'mobile_phone',
'label'=>'Mobile Number',
'rules'=>'required'
),
array(
'field'=>'email',
'label'=>'Email',
'rules'=>'required|is_unique[clients.email]|valid_email'
),
);
$this->load->library('form_validation');
$this->form_validation->set_rules($config);
if($this->form_validation->run() == FALSE){
$data['errors'] = validation_errors();
}else{
$data=array(
'img_path'=>$upload_data['file_name'],
'firstName'=>$_POST['firstName'],
'email'=>$_POST['email'],
'city'=>$_POST['city'],
'mobile_phone'=>$_POST['mobile_phone'],
);
$this->mdl_clients->add($data);
$data['success'] = 1;
$data['errors']= 0;
}
}
$data['title'] = 'Add Client Database';
$data['main_content'] = 'clients/add';
echo Modules::run('templates/admin', $data);
}
and my view file .. add.php
<? if($success==1) {?>
<div class="alert alert-success">
<a class="close" data-dismiss="alert" href="#">×</a>
Data Has been Updated !
</div>
<? } ?>
<?php if($errors) { ?>
<div class="alert alert-error" >
<a class="close" data-dismiss="alert" href="#">×</a>
<?=$errors?>
</div>
<? } ?>
<?php $attributes = array('class' => 'form-horizontal');
echo form_open_multipart('clients/add', $attributes); ?>
<fieldset>
<!-- Address form -->
<h2>Client Information</h2>
<hr />
All Fields Marked with <span style="color: red;">*</span> is necessary .
<hr />
<!-- Upload input-->
<div class="control-group">
<label class="control-label">Upload<span style="color: red;">*</span></label>
<div class="controls">
<input name="userfile" name="userfile" type="file"
class="input-xlarge">
<p class="help-block"></p>
</div>
</div>
<!-- firstName input-->
<div class="control-group">
<label class="control-label">First Name<span style="color: red;">*</span></label>
<div class="controls">
<input id="firstName" name="firstName" type="text" placeholder="First Name"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
</div>
<!-- Email input-->
<div class="control-group">
<label class="control-label">E-Mail<span style="color: red;">*</span></label>
<div class="controls">
<input id="email" name="email" type="text" placeholder="A Valid Email Address"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
</div>
<!-- City input-->
<div class="control-group">
<label class="control-label">City<span style="color: red;">*</span></label>
<div class="controls">
<input id="city" name="city" type="text" placeholder="City Name"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
<!-- Mobile input-->
<div class="control-group">
<label class="control-label">Mobile Number<span style="color: red;">*</span></label>
<div class="controls">
<input id="mobile_phone" name="mobile_phone" type="text" placeholder="Current Mobile Phone Number"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
</div>
<!-- Button -->
<div class="control-group">
<div class="controls">
<button class="btn btn-success">Add to Database</button>
</div>
</div>
</fieldset>
</form>
Assuming an input element of:
<input type="file" name="image" id="image">
Change the following line:
!$this->upload->do_upload()
to:
!$this->upload->do_upload('image')
Please let me know if you face any problem.
UPDATE
If you want to send it to the template then do something like this:
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg',$error['error']);
redirect('controller_name/function_name','refresh');
}
Let me know if this works for you.
While doing the form validation you are not taking into consideration if there were upload errors or not. You should check if there were upload errors or not than proceed with the form validation
if($data['errors'] != '')
{
//do something, probably redirect back to the view and show the errors
}
else
{
if($this->form_validation->run() == FALSE)
{
$data['errors'] = validation_errors();
}
else
{
$data=array(
'img_path'=>$upload_data['file_name'],
'firstName'=>$_POST['firstName'],
'email'=>$_POST['email'],
'city'=>$_POST['city'],
'mobile_phone'=>$_POST['mobile_phone'],
);
$this->mdl_clients->add($data);
$data['success'] = 1;
$data['errors']= 0;
}
}