CakePHP 5 complex search (with and without AJAX)

Hey,

I did this: CMS Tutorial - Creating the Articles Controller - 5.x

CREATE TABLE articles (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    title VARCHAR(255) NOT NULL,
    slug VARCHAR(191) NOT NULL,
    body TEXT,
    published BOOLEAN DEFAULT FALSE,
    created DATETIME,
    modified DATETIME,
    UNIQUE KEY (slug),
    FOREIGN KEY user_key (user_id) REFERENCES users(id)
) CHARSET=utf8mb4;

CREATE TABLE tags (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(191),
    created DATETIME,
    modified DATETIME,
    UNIQUE KEY (title)
) CHARSET=utf8mb4;

CREATE TABLE articles_tags (
    article_id INT NOT NULL,
    tag_id INT NOT NULL,
    PRIMARY KEY (article_id, tag_id),
    FOREIGN KEY tag_key(tag_id) REFERENCES tags(id),
    FOREIGN KEY article_key(article_id) REFERENCES articles(id)
);

How to add search form to index action?

I would like:

  • Published or not (radio button);
  • Input text search, LIKE or better idea in the title and body;
  • Choose the tags (select).
  • Order by tags count.

View file (templates/Articles/index.php):

echo $this->Form->create($article);
echo $this->Form->control('published', ['type' => 'checkbox']);
echo $this->Form->control('keywords');
// Tags from controller, how to?
echo $this->Form->select('order', ['asc' => 'A-Z', 'desc' => 'Z-A'], ['default' => 'asc']);
echo $this->Form->end();

How does this work on the controller side? I would like know AJAX (with jQuery or another) and without AJAX.

Thank you very much! :pray:

To begin with, implement the cakephp search plugin. GitHub - FriendsOfCake/search: CakePHP: Easy model searching

1 Like

+1 for this - very easy to implement

you need to loop the data in your index first, then check if there`s a query params that contain keywords