currently my autocomplete works in displaying the first name of the user, but I want to concatenate the first name, last name and etc. How do I achieve this in the following code?
<script type="text/javascript">
$(function() {
$(".suggest").autocomplete({
source: function( request, response ) {
$.ajax({
url: '<?php echo $this->Html->url(array('controller' => 'searches', 'action' => 'suggestUser')); ?>',
dataType: "json",
data: {
//request.term is the value of the current textbox.
term: request.term
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.User.firstName,
value: item.User.firstName
}
}));
}
});
},
minLength : 1
});
});
In my controller, the following codes below is my logic to search for that field.
function suggestUser() {
if (isset($_GET["term"])) {
$term = $_GET["term"];
$result = $this->User->find('all', array(
'conditions' => array(
'User.firstName LIKE' => $term . '%'
),
'fields' => array(
'firstName'
)
));
if ($term) {
$this->set('results', $result);
$this->view = 'Json';
$this->set('json', 'results');
}
}
}
http://book.cakephp.org/view/1588/virtualFields
It is really simple I realised. I managed to resolve it.
label: item.User.firstName + " " + item.User.lastName,
value: item.User.firstName + " " + item.User.lastName
You also need to append the lastName field in.
'fields' => array(
'firstName',
'lastName',
)
Related
I have been trying to make an autocomplete dropdown list but I really have no idea on how to do it. I have found an example on youtube but sadly it is not for cakephp. Here is the link if you are curious: https://www.youtube.com/watch?v=S6yCBggCKl0&t=305s. Please help me.
The CakePHP version of the project I'm working with is 3.8.
Here are the code the I come up with so far:
view:
$('.js-data-example-ajax').select2({
ajax: {
url: "<?php echo Router::url(["controller"=>"VScripts","action"=>"searchTask"]); ?>",
dataType: "json",
delay: 250,
data: function (params) {
return {
q: params.term,
};
},
processResults: function (data) {
return {
results: data,
};
},
cache: true
},
placeholder: 'Type atleast 1 digit to search',
minimumInputLength: 1
});
Controller:
public function searchTask()
{
$this->autoRender = false;
$term = $this->request->query['q'];
$select = array(
'task_id' => 'id',
);
$tasksTable = TableRegistry::getTableLocator()->get('Tasks');
$tasks = $tasksTable
->find()
->select($select)
->from('tasks')
->where(['task_id' => '%' . $term . '%'])
->limit(10)
->order(['task_id' => 'ASC'])
->execute()
->fetchAll('assoc');
$result = array();
foreach ($tasks as $task) {
$id = $task['task_id'];
$result[] = array('id' => $id, 'text' => $id);
}
echo json_encode($result);
}
So I have this Form in Blade
{!! Form::select('jobslist[]', $jobs, null, ['id' => 'jobs', 'class' => 'form-control jobs mav-select', 'multiple', 'style' => 'width: 60%; margin-top: 10px;', 'disabled'=>'disabled']) !!`}
I am trying to load $jobs data using Ajax, so I rewrote the form as
{!! Form::select('jobslist[]', [], null, ['id' => 'jobs', 'class' => 'form-control jobs mav-select', 'multiple', 'style' => 'width: 60%; margin-top: 10px;', 'disabled'=>'disabled']) !!}
And added onload script underneath
function loadData(card){
$.ajax({
type: 'POST',
url: '/loadJobs/',
data: {name: card, element: '{{$posting->id}}'},
dataType: 'json',
success: function (response) {
console.log(response);
$("#jobs").html('');
$("#jobs").html(response.options);
})
},
error: function(response){
console.log('Error: ', response["responseText"]);
}
});
}
Through console log I can verify that I am hitting the controller and obtaining data in the format
Object:
options:
27969: "2016-230 :: PL"
27974: "2016-231 :: ML"
27989: "2016-233 :: RF"
how should I pass it to the select box?
You can use append to add the items to select in the success function:
success: function(response){
...
$('#jobs').append('<option value='+response.id+'>' +response.name+ '</option>')
...
}
There you have it, just change 'id' and 'name' as necessary, I hope it helps.
//...
success:function(response){
var len = response.length;
$("#jobs").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#jobs").append("<option value='"+id+"'>"+name+"</option>");
}
}
//...
success: function(data){
console.log('success');
console.log(data);
jobs = data;
$.each(data, function(key, target){
//Use the Option() constructor to create a new HTMLOptionElement.
var option = new Option(target.name, target.id);
//Convert the HTMLOptionElement into a JQuery object that can be used with the append method.
$(option).html(target.name);
//Append the option to our Select element.
$("#jobs").append(option);
//$("#jobs").append("<option> An Option </option>");
});
/
},
i created a form using AJAX because i have several alternatives concerning the fields.
I have correct information in my javascript and make tests... my first select use the following function and generates form
function setParentSector() {
$("#listSectors").html("");
$("#createSector").html("");
if($('#langname option:selected').val() !=0) {
var obj = { 'id': $('#langname option:selected').val() };
if (obj['id'] != 1) {
ajaxSectors(obj);
}
else
{
// another form generated here ...
$('#createSector').append("something else");
}
}
};
I use a "classical" ajax ..
function ajaxSectors(objSetParent) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/admin/ajax/sectorParent',
type: 'post',
dataType: 'json',
async: true,
success: function (result) {
$('#listSectors').append("<label for='langname'>label </label> " +
"<select class='form-control m-input m-input--air' id='sectors' onclick='setLangTranslation()'>" +
"<option value='0' selected>Select value</option></select>" +
"<span class='m-form__help' id='existsAlready'>");
var count = result.length;
for (var i = 0; i < count; i++) {
if (result[i].deleted_at === null) {
$('#sectors').append("<option value='" + result[i].sector_id + "'>" + result[i].sectname + "</option>");
}
else {
console.log("peanuts");
}
}
},
data:objSetParent,
error: function (result) {
},
complete: function (result) {
//console.log("complete");
}
});
}
This part of code works fine and i display what i want...
When I want to save into DB the form, I plan to use the store method and I create the $request->validate()
In the store method I have :
$request->validate([
'admin' => 'required',
'langname' => 'required',
'sectname' => 'required',
'sectshortname' => 'nullable',
]);
return view ('test')
The test view contains just in order to see what i post ..
If i keep the validate part, the page is just refreshed and not validated...
Without the request validate I display the view and i just see the value of the input with the token.
Thanks for your answers. Let's hope my question is "clear" enough
Use this code I hope this code works for you please use this Use Validator;
$rules = [
'admin' => 'required',
'langname' => 'required',
'sectname' => 'required',
'sectshortname' => 'nullable',
];
$data = $request->all();//or you can get it by one by one
$validator = Validator::make($data , $rules);
if ($validator->fails()) {
$error=[];
$errors = $validator->messages();
foreach($errors->all() as $error_msg){
$error[]= $error_msg;
}
return response()->json(compact('error'),401);
}
return view ('test')
I have a CListView which I want to filter using Ajax. I have 2 textfields. Now they both filter the same column: titel. I'm searching quite some time now, but I can't seem to figger out why they both filter the titel and not the locatie too..
It's my first time to use Ajax so, i'm afraid I don't know exactly how to pass the right parameters at the moment and am kind of lost. Someone who can help me?
So here's my view:
<?php echo CHtml::beginForm(CHtml::normalizeUrl(array('kunstwerk/index')), 'get', array('id'=>'filter-form'))?>
<?php echo CHtml::textField('string', (isset($_GET['string'])) ? $_GET['string'] : '', array('id'=>'locatie'));?>
<?php echo CHtml::textField('string', (isset($_GET['string'])) ? $_GET['string'] : '', array('id'=>'titel'));?>
and..
Yii::app()->clientScript->registerScript('search',
"var ajaxUpdateTimeout;
var ajaxRequest;
$('input#titel').keyup(function(){
titel = $(this).serialize();
clearTimeout(ajaxUpdateTimeout);
ajaxUpdateTimeout = setTimeout(function () {
$.fn.yiiListView.update(
// this is the id of the CListView
'ajaxListView',
{data: titel}
)
},
// this is the delay
300);
});
$('input#locatie').keyup(function(){
locatie = $(this).serialize();
clearTimeout(ajaxUpdateTimeout);
ajaxUpdateTimeout = setTimeout(function () {
$.fn.yiiListView.update(
// this is the id of the CListView
'ajaxListView',
{data: locatie}
)
},
// this is the delay
300);
});"
);
and..
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'sortableAttributes'=>array(
'titel'
),
'id'=>'ajaxListView',
));
?>
Here's my controller:
public function actionIndex($string = '')
{
$criteria = new CDbCriteria();
if( strlen( $string ) > 0 )
$criteria->addSearchCondition( 'titel', $string, true, 'OR' );
$criteria->addSearchCondition( 'locatie', $string, true, 'OR' );
$dataProvider = new CActiveDataProvider( 'Kunstwerk', array( 'criteria' => $criteria, ) );
//$dataProvider=new CActiveDataProvider('Kunstwerk');
$this->render('index',array(
'dataProvider'=>$dataProvider,
'bedrijven' => Bedrijf::model()->findAll(),
));
}
Im new to PHP.
I'd like to build a module and i need json to pass specific content type fields.
Im trying with this but i dont know how to deal with callback function.
here is my ajax in .js
$.ajax({
type: 'GET',
url: '/mappy/ajax/poi',
data: {
nid: nid
},
dataType: 'json',
success: function(data){
alert(data)
}
});
})
here is my php in .module
function mappy_menu() {
$items = array();
$items['/mappy/ajax/poi'] = array(
'title' => 'Mappy Pois',
'page callback' => 'mappy_get',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function mpapy_get() {
$nid = $_GET('nid');
$title = field_get_items('node', $node, 'field_title');
$result = json_encode(
db_query("SELECT nid,title FROM {node}", $nid)
);
drupal_json_output($result);
print $result;
}
Many thanks for advice.
Once you get the JSON response you need to convert it to a javascript array. For that, you can do:
var javaArray = $.parseJSON(data);
Now you can retrieve the data, using code like javaArray['key1']['key2'], etc.
.js
$.ajax({
type: 'GET',
// Do not use slash at the beginning, use Drupal.settings.basePath instead
url: Drupal.settings.basePath + 'mappy/ajax/poi',
data: {
nid: nid
},
dataType: 'json',
success: function(data) {
alert(data)
}
});
.module
function mappy_menu() {
$items = array();
// Never use slash at the beginning in hook_menu
$items['mappy/ajax/poi'] = array(
'title' => 'Mappy Pois',
'page callback' => 'mappy_get',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function mappy_get() {
$node = node_load($_GET('nid'));
// Or equivalent
/* $node = db_select('node', 'n')
->fields('n', array('nid', 'title'))
->condition('n.nid', $_GET('nid')))
->execute()
->fetchAll(); */
$values = array(
'nid' => $node->nid,
'title' => $node->title
);
#$result = json_encode(
# db_query("SELECT nid,title FROM {node}", $nid)
#);
// drupal_json_output already print the value
// print $result;
drupal_json_output($values);
drupal_exit();
}