I am developing a custom module named as people finder. I am unable to fetch related data that I search rather it renders all the row on any inputs. If anyone know kindly help me. Here a is code snippet of PeopleFinderController.php:
namespace Drupal\people_finder\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Database;
use Symfony\Component\HttpFoundation\Request;
class PeopleFinderController extends ControllerBase {
protected $database;
public function __construct(Connection $database) {
$this->database = $database;
}
public function searchResults(Request $request) {
$connection = Database::getConnection();
$user_details = [];
// Retrieve search criteria from the request.
$name = $request->query->get('name');
$department = $request->query->get('department');
$room_no = $request->query->get('room_no');
$telephone = $request->query->get('telephone');
// Construct the database query.
$query = $connection->select('people_data', 'p')
->fields('p', ['name', 'department', 'room_no', 'telephone']);
// conditions based on search criteria.
if (!empty($name)) {
$query->condition('p.name', '%' . $connection->escapeLike($name) . '%', 'LIKE');
}
if (!empty($department)) {
$query->condition('p.department', '%' . $connection->escapeLike($department) . '%', 'LIKE');
}
if (!empty($room_no)) {
$query->condition('p.room_no', '%'. $connection->escapeLike($room_no) . 'LIKE');
}
if (!empty($telephone)) {
$query->condition('p.telephone', '%' . $connection->escapeLike($telephone) . '%', 'LIKE');
}
// Execute the query and fetch results.
$results = $query->execute()->fetchAll();
foreach ($results as $result) {
// Build rows for the table.
$user_details[] = [
'name' => $result->name,
'department' => $result->department,
'room_no' => $result->room_no,
'telephone' => $result->telephone,
'email' => $result->email,
];
}
// Build the render array for displaying search results.
$header = [
'name' => $this->t('Name'),
'department' => $this->t('Department'),
'room_no' => $this->t('Room_No'),
'telephone' => $this->t('telephone'),
'email' => $this->t('Email'),
];
// Return the table as render array.
return [
'#type' => 'table',
'#header' => $header,
'#rows' => $user_details,
'#empty' => $this->t('No users found.'),
];
}
}