Drupal PHP Form Submit On Enter - php

I am trying to troubleshoot a PHP form within a Drupal 7 site. At the moment, the form can only be submitted if the user clicks the button. I would like to enable submission with "Enter" key. How can I do this?
Here is the relevant code:
$form['search']['search_button'] = array(
'#type' => 'button',
'#value' => 'Search',
'#ajax' => array(
'callback' => 'ajax_search_callback',
// 'wrapper' => 'search-results',
'wrapper' => 'search',
'method' => 'replace',
'effect' => 'fade',
'event' => 'click',
),
);
I suspect that I need to change 'event' field or add another field.

I implemented this by adding this piece of code on textfield on which i want to trigger submit event:
$form['field_name']['#attributes']['onkeypress'][] if (event.keyCode == 13) {jQuery('.submit-selector').mousedown();}

You need to add the keypress attribute to the ajax array and set it to TRUE.
It is explained in the form api documentation, here.
EDIT :
The first solution works only for one single input field. To add keypress event on the form, you must add an "onkeypress" attribute to the form by adding it in the attributes array:
$form['#attributes']['onkeypress'] = 'if(event.keyCode==13){this.form.submit();}';
Where 13 is the keyCode for Enter (or return for a mac).
I don't know if it's the cleanest solution, but it should work.

This worked for me:
$form[FORM_ITEM]['#attributes']['onkeypress'][]="jQuery('input').keydown(function(e) {if (e.keyCode == 13) {e.preventDefault(); jQuery('#edit-submit').mousedown();}});";

I'm not an expert in JS, but this is how i would have tackled the issue myself.
I didn't test it, but I suggest adding something like the following statement in your js file
$( document ).ready(function() {
$( "#target" ).keypress(function() {
if ( event.which == 13 ) {
$('my_form').submit();
}
});
});
Basically, you look for the keypress event 13, then you submit your form.
I hope your form doesn't have any textarea tags, because you might face some user issues.
EDIT: Where to add the Javascript?
I assume you are writing a custom module to generate your form, so you can add a path to the .info file of your module or use the function drupal_add_js("your_path_to_js_file"); which is probably a better solution here.
I hope it helps.
Cheers

Related

Display select2 generated inputfields only with CakePHP 2.8.x form helper

UPDATE:
Already found out what the issue was. Had to add 'multiple' => 'multiple' to the input array from this->Form->input. When i added that line, the input field from Cake will be replaced by Select2.
I'm using CakePHP 2.8.x in combination with the Select2 plugin in order to get multiple select boxes, like this.
Here's my issue:
I have created an input field with the CakePHP form helper:
$sizes = array('s' => 'Small', 'm' => 'Medium', 'l' => 'Large');
echo $this->Form->input('size',
array(
'options' => $sizes,
'class' => 'form-control haai'
)
);
Cake creates the id TransferSize for me, that i can use for the Select2 plugin:
<script type="text/javascript">
$(document).ready(function(){
//Select2
$("#TransferSize").select2({
placeholder: "Select your emailaddresses"
})
});
</script>
What happens when i do this, is that Select2 generates extra input fields within Cake's input field.
Is there a way to hide the input field that CakePHP produces and display the input field that the select2 plugin generates in the hidden CakePHP input field? Or is there a better solution that any of you know?
Help will be greatly appreciated ofcourse! :)
All you've to do is put your script before the </body> tag just like this:
<script type="text/javascript">
$(document).ready(function(){
//Select2
$("#TransferSize").select2({
placeholder: "Select your emailaddresses"
})
});
</script>
</body>

How to call Ajax on drop down in CakePHP

I am new to PHP and CakePHP. I m trying to call Ajax on changing drop down item. I have done it for a link as below code
echo $this->Html->link('TestLink', array('controller'=>'Tutors','action'=>'getData',$iid), array('class'=>'js-ajax'));
but unable to apply on drop down. I have used the code for drop down as below
echo $this->Form->input('My City', array('empty'=>'Select City','options' => $cities));
here, where to put code to call ajax.
Please help.
You should bind an ajax event to js-ajax
$('.js-ajax').on('change', function(){
// do some ajax here.
});
`
If its just the selector you're looking to add to trigger the ajax, then do the following:
echo $this->Form->input('My City', array(
'empty'=>'Select City',
'options' => $cities,
'class' => 'js-ajax'
));
Then you can have your javascript onchange called with this selector
Why you don't use jquery to do this?
put in your webroot and call in your layout(app/view/layouts)
$(document).ready(function(){
//your code
$("#youFieldId").change(function(){
//Your logic
});
});

Drupal 7 collapsible fieldset issues with ajax

I am sending data via ajax to my PHP callback function inside my custom module... Everything is working great. The problem I am having is: the html i am returning and rendering in the ajax complete funciton is composed of fieldsets which wont expand/collapse. Things i have tested :
1). If I render the same html ( fieldsets ) into one of the custom blocks in that same module, they work great, the collapse and expand.
2). I have tried including this inside the callback function,
drupal_add_js('misc/form.js');
drupal_add_js('misc/collapse.js');
inside the fieldset render array,
return array(
'#type' => 'fieldset',
'#title' => t($title),
'#attributes' => array(
'class' => $class,
),
'#attached' => array(
'js' => array(
'misc/form.js',
'misc/collapse.js',
),
),
);
The
$class
variable contains collapsed and collapsible. I have also tried using
#theme => 'fieldset'
Instead of #type => 'fieldset'
the javascript files
misc/collapse.js
misc/form.js
are already being included from a different function inside my module. And looking at the source of the page, are indeed being included to the head of the page.
This has to be related to bringing them in via ajax, I know when you bring elements into the document via ajax, in-order to set events for those new elements you have to use
$(document).on('event', 'class', function(){
//code here
});
and I am wondering if this could be the reason that the fieldsets wont collapse/expand.
If you get data with AJAX with jQuery once you have to use Drupal.behaviors like this:
Drupal.behaviors.MYBEHAVIOR = {
attach: function (context, settings) {
$('MYELEMENT.MYBEHAVIOR', context).once('MYBEHAVIOR', function () {
// Apply the MYBEHAVIOR effect to the elements only once.
});
}
};
See more at the js documentation https://drupal.org/node/756722

How can I submit my Drupal form to any other internal page?

I'm having a problem with Drupal forms. Can't think of a way to solve it and I was wondering if any brain out there has the solution to my problem.
I have this form:
<?php
function mymodule_myform(){
$form['#action'] = url('search/cards');
$form['whatwhere']['what'] = array(
'#type' => 'textfield',
'#title' => t('What?'),
'#maxlength' => 80,
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Search'),
);
}
?>
Which, as you can see, is supposed to submit all info to www.example.com/search/cards.
This will indeed submit my form to the desired URL. However, without the mymodule_menu() hook defining the path, it will end in a 404.
So I add:
<?php
function mymodule_menu(){
$items['search/%'] = array(
'title' => t('Search Results'),
'page callback' => 'mymodule_main',
'access arguments' => array('access content'),
'file' => 'mymodule.inc',
);
}
?>
And, at mymodule.inc file I'll create my function mymodule_main():
<?php
function mymodule_main(){
print_r($_POST);
die(); // ### Note the die(); ###
return 'Just searched: '. $_POST['what'];
}
?>
If I leave it exactly like it is, of course PHP will end the script execution right after printing my form info on the screen. All good!
However, if I remove the die(), it seems the function is called twice, and the second call does not have $_POST filled up anymore.. Seems mymodule_menu() overrides in some way whatever the form submit handler is doing...
The question is: How can I submit my form to any other internal page without having the 404 and keep my form info?
Thanks in advance.
I think you need to use the method described in http://api.drupal.org/api/function/search_box_form_submit/6
function MODULE_block_form_submit($form, &$form_state)
{
if (isset($_REQUEST['destination'])) {
unset($_REQUEST['destination']);
}
if (isset($_REQUEST['edit']['destination'])) {
unset($_REQUEST['edit']['destination']);
}
$form_state['redirect'] = 'search/cards/'. trim($form_state['values']['whatwhere']);
}
I don't know exactly, but maybe your code conflicts with drupal's builtin search module?
After some debate # drupal forums (which can be followed here) conclusion is that: it is not possible to have a menu callback handling form results. You can instead, use a form submit handler (as always) and then redirect to your menu callback.
It's not a POST to the menu callback but it's as good as it gets.
Thanks for your help.

How to Zend_Dojo_Form_Element_FilteringSelect onchange submit

Well the title pretty much says it all. I had:
$strata = new Zend_Form_Element_Select('strata');
$strata->setLabel('Select a strata: ')->setMultiOptions($this->stratalist)->setAttrib('onChange', 'this.form.submit()');
Then I need to use some fancy dojo form elements in other forms. So I decided to make them all look the same and did this:
$strata = new Zend_Dojo_Form_Element_FilteringSelect('strata');
$strata->setLabel('Select a strata: ')->setMultiOptions($this->stratalist)->setAttrib('onChange', 'this.form.submit()');
It shows up and looks fine, but the form is not submitted when I change the FilteringSelect. If I look at the HTML that is rendered, sure enough:
<select name="strata" id="strata" onChange="this.form.submit()">
I suspect that Dojo elements cannot or do not work like this. So how do I make this form submit when I change the FilteringSelect?
Here it is:
When defining the form, give it an id:
$this->setName('StrataSelect');
or
$this->setAttrib('id', 'StrataSelect');
Then the onChange event uses getElementById:
$strata = new Zend_Dojo_Form_Element_FilteringSelect('strata');
$strata->setLabel('Select a strata: ')->setMultiOptions($this->stratalist)->setAttrib('onChange', "document.dojo.byId('StrataSelect').submit();");
or
$strata->setLabel('Select a strata: ')->setMultiOptions($this->stratalist)->setAttrib('onChange', "document.getElementById('StrataSelect').submit();");
Why this now works and none of the "old school" submit() calls probably has something to do with dojo handling the onchange event. So submit or this.form are not objects, methods, etc etc etc.
I don't want to put any javascript this form depends on into the view. I want this form to be "portable". So therefore I don't want to use dojo.connect
There are probably better ways to do this. So I'll leave this unanswered for now.
Do you have parseOnLoad enabled? If you're building the form in php you can do this:
$form = new Zend_Form_Dojo();
$form->addElement(
'FilteringSelect',
'myId',
array(
'label' => 'Prerequisite:',
'autocomplete' => true,
'jsId' => 'myJsId',
),
array(), //attributes
array( //your select values
'id1' => 'name1',
'id2' => 'name2',
'id3' => 'name3',
)
);
you might need to set a few attributes on your $form.
try this:
$form->setAttribs( array('jsId'=>'MyFormName') );
Then in your onClick:
MyFormName.submit()
If your form passes validation (presuming you have some), it should submit.

Categories