Edit formatting parameters passed by Cakephp URL 3

Asked

Viewed 227 times

1

I have a unique field form, a input type="text", when the form is submitted to URL is as follows:

http://localhost:8765/products/search?search=notebook

I would like it to be as follows when submitting the form:

http://localhost:8765/products/search/notebook

Typing the URL above manually works perfectly (I created a method that is able to pick up the content after search/ since it is in the format above, I also created a specific route to have the URL above)

Created route code (Routes.php):

$routes->connect('/products/search/:search', ['controller' => 'Products', 'action' => 'search'],
        [':search' => '\w+', 'pass' => ['search']]);

Productscontroller.php code (method responsible for the search action)

public function search($search)
    {
        if($this->request->is('get'))
        {
            //$product = $this->request->params['pass'];
            $this->paginate = [
                'fields' => ['product_name', 'quantity', 'sold', 'description', 'price', 'old_price', 'thumbnail'],
                'conditions' => ['product_name LIKE' => '%'.$search.'%'],
                'order' => ['price' => 'DESC'],
                'limit' => 3
            ];

            $this->set('products', $this->paginate($this->Products));
        }
    }

Form code:

<?= $this->Form->create(null, ['url' => ['controller' => 'Products', 'action' => 'search'], 'type' => 'get', 'id' => 'search-form', 'class' => 'navbar-form span7 text-center']) ?>
            <button class="btn btn-info" title="Favorite o Site">
                <span class="glyphicon glyphicon-star"></span>
            </button>
            <?= $this->Form->text('search', ['class' => 'form-control', 'placeholder' => 'Search']) ?>
            <?= $this->Form->button('Buscar <span class="glyphicon glyphicon-search"></span>', ['type' => 'submit', 'class' => 'btn btn-default']) ?>
        <?= $this->Form->end() ?>

OBS1: I imagine the modification should be made in this form (It’s just an assumption).

OBS2: I’m using the Cakephp 3

  • The format [...]search?search=notebook is the standard of the method. To [...]search/notebook I believe only by manipulating the URL at Submit time with JS.

1 answer

0


I used the lib jQuery so that the form is submitted it suppress its default behavior, create the new url and do the redial:

$("#search-form").submit(function(event){
    event.preventDefault(); // suprimir o comportamento padrão
    action = $(this).attr('action') + '/' + document.getElementById('search').value; // criar a nova url no formato desejado
    window.location.href = action; //faz a redireção:
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.