Triggering event manually in JS Helper CakePHP
Asked Answered
U

1

6

I stuck in a situation. I am using JS Helper. I used the following code.

<?php $this->Js->get('#client_id')
        ->event('change', $this->Js->request(array('action' => '../ajax/get_client_location_and_process'),
                   array('update' => '#client_location_process',
                     'async' => false, 
                     'dataExpression' => true,
                     'method' => 'post',
                     'evalScripts' => true,
                     'data' => $this->Js->serializeForm(array('isForm' => True, 'inline' => True))
                     )
                   )
        );

I want to trigger the change event on page load. If I am using document.ready method then it is not working. and I unable to find the JS Helper method where we can explicitly trigger some event on controls. Please suggest the code how can I perform JQuery trigger() like functionality on form elements whenever I need it.

Uri answered 3/7, 2012 at 6:29 Comment(2)
I am trying to find out JQuery.trigger() equivalent code in JsHelper. Any help much appreciated.Uri
Personally I don't think the JSHelper was made for this sort of thing, it's really only for handy ajax requests from my experience. I would say you'll make thind a lot clearer/easier in the long term if you just write out the JS in a .js file...Jerboa
A
13

Since you already found out about .trigger() in jQuery, you can just use it along with your view code:

<?php 
    // Your view code
?>
<script>$('#client_id').trigger('change');</script>

Alternatively, if you still prefer to do it via PHP, you can perhaps make your own helper, eg.:

<?php 
class ArunjsHelper extends AppHelper {
    public $helpers = array('Html');

    function trigger($element, $event, $options = array()) {
        return $this->Html->scriptBlock("$('$element').trigger('$event');");
    }
}

Add ArunjsHelper to $helpers at controller:

<?php
class SomeController extends Controller {
    public $helpers = array('Arunjs');

    // Your controller code
}

You can then call it from view:

<h1>Hello</h1>
<p>Your usual view HTML code</p>

<?php // Trigger the change event ?>
<?php echo $this->Arunjs->trigger('#client_id', 'change'); ?>
Arlyn answered 20/7, 2012 at 14:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.