Masonite Project - Autocomplete Search with Select2 JS Example
In this quick example, we will see step by step how to incorporate Select2.js in our Masonite Project page.
Select2 gives us a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options. More info to the following link Select2 .
Masonite Installation
mkdir masonite-select2
cd masonite-select2
Activating Our Virtual Environment
python -m venv venv
source venv/bin/activate
Install Masonite
pip install masonite
Start project
project start .
Start Development Server
python craft serve
Add Dummy Users
Now, we need to run default migrations, so we have created new users table. So let's run migration command:
python craft migrate
We are using the default DB configuration that is coming with Masonite and it is sqlite.
Now we will create some users using the user factory.
We need to do the following steps:
1) In the config folder we are creating a new file with name config/factories.py
.
2) In factories.py
, we are putting the following configuration.
# config/factories.py
from masoniteorm import Factory
from app.models.User import User
def user_factory(faker):
return {
'name': faker.name(),
'email': faker.email(),
'password': 'secret'
}
Factory.register(User, user_factory)
3) We connect to tinker
python craft tinker
4) We are executing the following commands:
from config.factories import Factory
users = Factory(User, 50).create()
That's it! We have now 50 users in our DB!
Create Controller
At this point, we will create a new controller as SearchController. This controller we will add two method, one to return view response and another for getting ajax requests replying back a json.
python craft controller SearchController
app/controllers/SearchController.py
from masonite.controllers import Controller
from masonite.views import View
from masonite.response import Response
from masonite.request import Request
from app.models.User import User
class SearchController(Controller):
def index(self, response: Response , view: View):
users= User.select('id','name as text').get().to_json()
return view.render("select2search",{'users':users})
def search(self, request: Request):
users= User.select('id','name as text').where('name','like','%'+request.input('q')+'%').get().to_json()
return users
Create Routes
In this is step, we will create route for our layout file and another one for getting data. So open our routes/web.py
file and add following route.
routes/web.py
from masonite.routes import Route
ROUTES = [Route.get("/", "WelcomeController@show"),
Route.get("/select2search", "SearchController@index"),
Route.get("/search", "SearchController@search"),
]
Create Template File
In last step, let's create select2search.html
(templates/select2search.html) for layout and lists all items code here and put following code:
<!DOCTYPE html>
<html>
<head>
<title>Masonite Select2 JS Autocomplete Search Example</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
</head>
<body>
<div class="container">
<h1>Masonite Select2 JS Autocomplete Search Example</h1>
<select class="js-example-basic-single" style="width:500px;" name="user_id"></select>
</div>
<script>
$(document).ready(function() {
$('.js-example-basic-single').select2(
{placeholder: 'Select a User',
data: {{ users | safe }}
}
);
$('.js-example-basic-single').on('select2:select', function (e) {
var data = e.params.data.id;
var url = 'http://127.0.0.1:8000/search';
window.location.href = url+'/'+data
});
});
</script>
</body>
</html>
You can open the following link to search the users:
http://127.0.0.1:8000/select2search
As you can see, it works!