Codeigniter auto suggestion text box - codeigniter

I'm using codeigniter in my project and want to implement a text box which suggests related word s from the data base. In this one I want to get the ID of the selected vehicle. But so far I was only able to retrieve the vehicle names with out IDs.
The code so far,
Model
function searchVehicle($name){
$this->db->like('Name', $name, 'both');
return $this->db->get('vw_vehicle_search')->result();
}
Controller
public function vehicle_search(){
$this->load->model('model_vehicle');
if(isset($_GET['term'])){
$result = $this->model_vehicle->searchVehicle($_GET['term']);
if(count($result)>0){
foreach($result as $object)
$arr_result[] = $object->Name;
echo json_encode($arr_result);
}
}
}
View
<script type="text/javascript">
$(document).ready(function(){
$('#vehicle_name').autocomplete({
source: "<?php echo base_url();?>vehicle/vehicle_search/?"
});
});
</script>
<div class="col-md-4">
<?php
$input_data = array(
'name' => 'vehicle_name',
'id' => 'vehicle_name',
'class' => 'form-control'
);
echo form_input($input_data)?>
</div>
How can I pass the id of the vehicle with this one and get the id when i select a vehicle to insert to the db.
Thank you.

Try it in this way:
controller:
public function vehicle_search(){
$this->load->model('model_vehicle');
if(isset($_GET['term'])){
$result = $this->model_vehicle->searchVehicle($_GET['term']);
if(count($result)>0){
foreach($result as $object)
$arr_result[] = array( 'label' => $object->Name, 'value' => $object->id);
echo json_encode($arr_result);
}
}
}
View:
$(document).ready(function(){
$('#vehicle_name').autocomplete({
source: "<?php echo base_url();?>vehicle/vehicle_search/?",
select: function(event, ui) {
event.preventDefault();
$("#vehicle_name").val(ui.item.label);
//$("#vehicle_name-hidden").val(ui.item.value);
},
focus: function(event, ui) {
event.preventDefault();
$("#vehicle_name").val(ui.item.label);
}
});
});

Related

Problem with edit function using a modal Laravel

I have the next function
public function edit($id)
{
if(request()->ajax())
{
$data = Tbl_Perimetro::findOrFail($id);
return response()->json(['result' => $data]);
}
}
public function update(Request $request, Tbl_Perimetro $user)
{
$rules = array(
'rif' => 'required',
'razon_social' => 'required',
'holdings_id' => 'required',
'pines_id' => 'required'
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json(['errors' => $error->errors()->all()]);
}
$form_data = array(
'rif' => $request->rif,
'razon_social' => $request->razon_social,
'holdings_id' => $request->holdings_id,
'pines_id' => $request->pines_id
);
Tbl_Perimetro::whereId($request->hidden_id)->update($form_data);
return response()->json(['success' => 'Datos actualizados satisfactoriamente.']);
}
My problem is that I would like to work with some models... and I know how to work with one model which is Tbl_Perimetro... I would like to work with another model called Tbl_Holding, But I'm using a modal to edit all this information.. here is the code of the modal:
$('#create_record').click(function(){
$('.modal-title').text('Add New Record');
$('#action_button').val('Add');
$('#action').val('Add');
$('#form_result').html('');
$('#formModal').modal('show');
});
$('#user_form').on('submit', function(event){
event.preventDefault();
var action_url = '';
if($('#action').val() == 'Add')
{
action_url = "{{ route('perimetro.store') }}";
}
if($('#action').val() == 'Editar')
{
action_url = "{{ route('perimetro.update') }}";
}
$.ajax({
url: action_url,
method:"POST",
data:$(this).serialize(),
dataType:"json",
success:function(data)
{
var html = '';
if(data.errors)
{
html = '<div class="alert alert-danger">';
for(var count = 0; count < data.errors.length; count++)
{
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if(data.success)
{
html = '<div class="alert alert-success">' + data.success + '</div>';
$('#user_form')[0].reset();
$('#user_perimetro').DataTable().ajax.reload();
}
$('#form_result').html(html);
}
});
});
$(document).on('click', '.edit', function(){
var id = $(this).attr('id');
$('#form_result').html('');
$.ajax({
url :"/perimetro/"+id+"/edit",
dataType:"json",
success:function(data)
{
$('#rif').val(data.result.rif);
$('#razon_social').val(data.result.razon_social);
$('#holdings_id').val(data.result.holdings_id);
$('#pines_id').val(data.result.pines_id);
$('#carteras_id').val(data.result.carteras_id);
$('#hidden_id').val(id);
$('.modal-title').text('Editar Registro');
$('#action_button').val('Editar');
$('#action').val('Editar');
$('#formModal').modal('show');
}
})
});
This is the button to edit the information
$button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Editar</button>';
I would like to know is it exist a way to work with two models in the same modal... In this way I only can work with one model at the same time...
I think I got what you mean...
What you can do is using a route with 2 variables passed, the first variable could be the id of the tbl_perimetro and the 2nd variable could be the id of the tbl_holding.
So, this would fit like this:
public function edit($id, $idholding)
{
if(request()->ajax())
{
$data = Tbl_Perimetro::findOrFail($id);
$data1 = Tbl_Holding::findOrFail($idholding);
$alldata = array($data, $data1); //----->THIS WILL BREAK YOUR JSON STRUCTURE BE CAREFUL
return response()->json(['result' => $alldata]);
}
}
And the same in the update function:
public function update(Request $request, Tbl_Perimetro $user, Tbl_Holding $holding)
{
...
}
Be careful editing your routes, because starting in laravel 6 (I think) the variables HAVE to be literal, so the new routes have to match the variable name of the function p.ex:
Route::get('editmodels/{id}/{idholding}','Controller#edit'); //<----This will work
Route::get('editmodels/{id}/{id2}','Controller#edit'); //<----This won't work
Hope it helps!!

Laravel 5.4 - Populate dropdown based on another dropdown selected value

I want when select one value from first dropdown to automatcly populate another dropdown based on first dropdown value.
My view:
<label for="category">Catégorie(s):</label>
{!! Form::select('category', $category,null, array('class' => 'form-
control')) !!}
<label for="brand">Marque:</label>
{!! Form::select('brand_name', $brand_name,null, array('class' => 'form-control')) !!}
My controller:
public function index()
{
$category = Category::pluck('categoryName', 'id');
$brand = Brand::pluck('brandName', 'id');
return view ( 'site.indexS',compact('brand','category') );
}
How to populate another dropdown? Any idea?
you can easily do it with a little bit of ajax and get method. May be you are trying to load brand depend on category lets roll :
Your controller:
public function index()
{
$category = Category::pluck('categoryName', 'id');
// no need to query brand here because we will load it depend on category
$brand = [];
return view ( 'site.indexS',compact('brand','category') );
}
// here we are adding another method in your controller which will return brand object depend on category id
public get_brand($categpry_id){
// hope your brand table contain category_id or any name as you wish which act as foreign key
$brands= Brand::where('category_id',$category_id)
->pluck('brandName','id');
return json_encode($brands);
}
Now in route we need to add this to hit this url :
Route::get('get-brand','YourControllerName#get_brand');
In view :
{{-- i am adding id for both dropdown --}}
Catégorie(s):
{!! Form::select('category', $category,null, array('id' => 'category_dropdown','class' => 'form-
control')) !!}
<label for="brand">Marque:</label>
{!! Form::select('brand_name', $brand_name,null, array('id' => 'brand_dropdown','class' => 'form-control')) !!}
now in our view file we need to use ajax, there is many other way i am preferring ajax here
<script type="text/javascript">
var url = "{{url('/')}}";
</script>
<script type="text/javascript">
$('#category_dropdown').on('change', function() {
$('#brand_dropdown').empty();
var id = $('#category_dropdown').val();
$('#brand_dropdown').html('<option selected="selected" value="">Loading...</option>');
var url = url + '/get-brand/'+id;
$.ajax({
url: url,
type: "GET",
dataType: "json",
success:function(data) {
//console.log(data);
$('#brand_dropdown').html('<option selected="selected" value="">Select Brand</option>');
$.each(data, function(key, value) {
$('#brand_dropdown').append('<option value="'+key+'">'+value+'</option>');
});
}
});
});
</script>

Auto Completion Ajax laravel

Hello I need to do autocompletion to some cities i already have in my db
so my code is like this :
View
<input type="text" name="ville" id="ville" class="small" placeholder="Entrer la ville souhaité">
<script type="text/javascript">
$(function() {
$( "#ville" ).autocomplete({
source:'{!!URL::route('autocomplete')!!}',
minlength:1,
autoFocus:true,
select:function(e,ui)
{
$('#ville').val(ui.item.value);
}
});
});
</script>
Controller
class VilleController extends Controller
{
public function autocomplete(Request $request)
{
$term = $request->term;
$queries = DB::table('ville')
->where('libelle_ville', 'like', '%'.$term.'%')
->take(6)->get();
foreach ($queries as $query)
{
$results[] = ['id' => $query->id, 'value' => $query->libelle_ville]; //you can take custom values as you want
}
return response()->json($results);
}
}
Routes
Route::get('/autocomplete', array('as' => 'autocomplete', 'uses'=>'VilleController#autocomplete'));
It doesn't tells me that I have an error and it doesn't show me any completion either.
Debug json request with laravel is a bit difficult, I recommend you to download this package
https://github.com/ARCANEDEV/LogViewer
or manually open the laravel log in storage/logs/laravel.log and see whats happened
Thanks to Stack and EddyTheDove I found out that the error is that aucomplete is not a function so I have to remove the barkets and $function so it would be something like this in the script tag
<script type="text/javascript">
$( "#ville" ).autocomplete({
source:'{!!URL::route('autocomplete')!!}',
minlength:1,
autoFocus:true,
select:function(e,ui)
{
$('#ville').val(ui.item.value);
}
});
</script>

Yii Framework: validate checkbox on view page

I'm new to the Yii Framework. Currently, I'm having a project which require me to use Yii framework. I would like to ask, is it possible for me to validate an attribute which is not save inside the database?
case:
I have a checkbox which require the user to tick on it in order to move to the next page. If the user doesn't tick on it, then it will prompt an error. How to I validate it in Yii format?
Can someone teach me how to change the validation below to fit Yii Format? where should the validation locate?
content in model.php
public $pdpa_agree;
public function rules()
{
array('pdpa_agree', 'required');
}
content in view.php
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'pdpaPolicy-form',
'enableAjaxValidation'=>true,
'type'=>'horizontal',
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
"autocomplete"=>"off", //turn off auto complete in FF
)
));
?>
<?php echo $data->pdpa_content; ?>
<p class="cb_pdpa" style="font-weight:bold"><?php echo $form->checkbox($data,'pdpa_agree'); ?> I have read and understood the above policies and hereby give consent for CTES to use my <pd>*personal data</pd> in accordance to the policies listed out above.</p>
<div class="form-actions">
<?php
/*$this->widget('bootstrap.widgets.TbButton', array(
'buttonType' => 'submit',
'type' => 'primary',
'label'=>$model->isNewRecord ? 'PolicyAgreement' : 'Continue Registration',
));*/
?>
<input type="button" name="submit" value="Continue Registration" onclick="validateAgreement()">
</div>
<?php $this->endWidget(); ?>
<script>
function validateAgreement()
{
if($("#pdpa_agree").is(':checked'))
{
window.location.href = 'register?sourceID=CTES';
return true;
}
else
{
alert("Please tick on the agreement checkbox in order to proceed the registration!");
return false;
}
}
</script>
How to turn to validation below to fit Yii Format?
<script>
function validateAgreement()
{
if($("#pdpa_agree").is(':checked'))
{
window.location.href = 'register?sourceID=CTES';
return true;
}
else
{
alert("Please tick on the agreement checkbox in order to proceed the registration!");
return false;
}
}
</script>
Yeah you can validate
Model.php
Delclare the variable you want to use
public $pdpa_agree;
public function rules()
{
array('pdpa_agree', 'required');
}
public function attributeLabels()
{
return array(
'pdpa_agree' => 'I have read and understood the above policies and hereby give consent for CTES to use my *personal data in accordance to the policies listed out above',
);
}
MyController.php
public function actionRegistration(){
$model = new Model();
if(isset($_POST['Model'])){
//Stuff to save Goes here
}
$this->render('registration');
}
view.php
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'pdpaPolicy-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'type'=>'horizontal',
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
"autocomplete"=>"off", //turn off auto complete in FF
)
));
?>
<?php echo $data->pdpa_content; ?>
<div class="form-actions">
$form->checkBox($model,'checkBox');
$form->labelEx($model,'checkBox');
$form->error($model,'checkBox');
</div>
<?php $this->endWidget(); ?>

CakePHP AJAX call

I am using CakePHP and this is my first project on this framework. I am going to send the value of an input to UsersController's check_username() action. And fill an element having id na with the string returned by check_username(). So far what I did is:
//in my form
<input type="text" name="data[User][username]" style="width: 60%" required="required" id="username" oninput="check_username(this.value)">
<label style="margin-left: 20px; color: red" id="na">Not Available!</label>
//after the form
<script type="text/javascript">
function check_username(un) {
$.ajax({
type: 'POST',
url: '/oes/users/check_username',
data: {username:un},
cache: false,
dataType: 'HTML',
beforeSend: function(){
$('#na').html('Checking...');
},
success: function (html){
$('#na').val(html);
}
});
}
</script>
//and my check_username() is
public function check_username(){
return 'Test string';
}
But this isn't working. Anybody know why or how to modify it so that it works?
It could be problem with your check_username controller action. CakePHP-way is to use JsonView class to send any data throw XHR (see http://book.cakephp.org/2.0/en/views/json-and-xml-views.html). It allows you to call any action with .json extension (ex.: /oes/users/check_username.json) and get response in serialized JSON format without manual conversion beetween array data and JSON.
This method is recommended for your needs, but not obligated, of course.
Now I think that CakePHP tries to render check_username view, but could not do this because you have not specified or created it. Try to change your action code to something like this:
public function check_username(){
$this->autoRender = false;
echo 'Test string';
}
Also, try not to use such code construction in the future.
CakePHP has a JS Helper to help write aJax functions. The only catch is to include jquery in your head our cake will throw jQuery errors.
Your Form:
<?php
echo $this->Form->create('User', array('default'=>false, 'id'=>'YourForm'));
echo $this->Form->input('username');
echo $this->Form->submit('Check Username');
echo $this->Form->end();
?>
The Ajax Function:
<?php
$data = $this->Js->get('#YourForm')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#YourForm')->event(
'submit',
$this->Js->request(
array('action' => 'checkUsername', 'controller' => 'user'),
array(
'update' => '#na',
'data' => $data,
'async' => true,
'dataExpression'=>true,
'method' => 'POST'
)
)
);
echo $this->Js->writeBuffer();
?>
The Function in User Controller
function checkUsername(){
$this->autoRender = false;
//run your query here
if ( $username == true )
echo 'Username is taken';
else
echo 'Username is not taken';
}
There are many examples through google. Here is a good one to visit.

Resources