I've recently incorporated select2 into my multiselect search filter, but I'm struggling to integrate it effectively.
Here's the method I'm using:
public function getContactByName($name)
{
return Contact::select(array('id', DB::raw('concat(first_name," ",last_name) as name')))->where(DB::raw('concat(first_name," ",last_name)'), 'like', "%$name%")->get();
}
This method retrieves records where the 'first_name' and 'last_name' are similar to the entered term in the URL, for example http://www.example.com/admin/get-contact-name/{name}.
The following route handles the request:
Route::get('admin/get-contact-name/{name}', 'AdminContactListController@getContactByName');
While this setup is functioning correctly, I need assistance setting it up with select2 and AJAX. I'm unsure about what options to include in the JS.
This is the form field I have in place:
<input name="contact_names_value" type="text" class="input-medium contact_names_value" id="contact_names_value">
If anyone could offer guidance on this matter, I would appreciate it. Thank you.
UPDATE: I'm experimenting with the code, trying to figure things out, but I'm struggling with understanding some elements like 'page'. Here's what I have at the moment, but it's not functional:
var name = $('#contact_names_value').val();
$('#contact_names_value').select2({
placeholder: 'Search contacts',
minimumInputLength: 3,
ajax: {
url: '/admin/get-contact-name' + name,
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10
};
},
results: function (data, page) {
return {results: data};
}
},
});
UPDATE: I believe I'm making progress and getting results through select2, but I'm encountering a JavaScript error. Here's what I have now.
Method:
public function getContactByName()
{
$name = Input::get('name');
return Contact::select(array('id', DB::raw('concat(first_name," ",last_name) as name')))->where(DB::raw('concat(first_name," ",last_name)'), 'like', "%$name%")->get();
}
Route:
Route::get('admin/get-contact', 'AdminContactListController@getContactByName');
Select2 JavaScript:
$('#contact_names_value').select2({
name: $('.select2-input').val(),
placeholder: 'Search contacts',
minimumInputLength: 3,
ajax: {
url: '/admin/get-contact' + name,
dataType: 'json',
data: function (term) {
return {
name: term
};
},
results: function (data) {
return {results: data};
},
dropdownCssClass: 'bigdrop'
},
});
Select2 JS Error:
Uncaught TypeError: Cannot call method 'toUpperCase' of undefined plugins.js:1549
C plugins.js:1549
a.fn.select2.defaults.formatResult plugins.js:1550
g plugins.js:1549
a.extend.populateResults plugins.js:1549
f.query.callback plugins.js:1549
(anonymous function) plugins.js:1549
a.extend.success plugins.js:1549
c jquery-1.9.1.min.js:3
p.fireWith jquery-1.9.1.min.js:3
k jquery-1.9.1.min.js:5
r
Any suggestions or advice on this issue?