How to hide a field on a form with jQuery - php

So I am working on hiding a input field, which I later plan to have dynamically loaded with the other form fields. I have created a small module to assist in this process.
/**
* Implements hook_form_alter().
*/
function editorhide_form_alter(&$form,$form_id){
//form id = artist_node_form
//title id = edit-title label: edit-title
global $user;
if($form_id == 'artist_node_form'){
if(in_array('editor', $user->roles)){
drupal_add_js("$(document).ready(function(){
$('#edit-title').css('display','none;');});"
);
}
}
}
however when looking at the element in question that needs to be hidden it doesn't go any where. My basic path I'm taking is:: Logged in as "editor"(admin privilages) -> Content -> Artist -> "Edit". At this point a light box (?) pops up with the fields to fill in to allow a person to person to add to the content. What am I missing..?
EDIT: Fixed the missing $(document) portion, still not hiding the field however.
Img:: http://imgur.com/sP2OlNg

Where you have this line...
$('#edit-title').css('display','none;');
Try making use of jQuery "hide" ability...
$('#edit-title').hide();
also, the CSS way isn't working because you have a semi-colon after 'none'. Doesn't need to be there.

maybe you should bind this event dynamically, in Jquery 1.x you can test it
if(in_array('editor', $user->roles)){
drupal_add_js("$(document).live("ready",function(){
$('#edit-title').css('display','none;');});"
);
}
or in jquery 2.x,
if(in_array('editor', $user->roles)){
drupal_add_js("$(document)bind('ready', function(){
$('#edit-title').css('display','none;');});"
);
}

Related

Add fragment to url during php runtime

Ok so here's my situation: I have a page with 5 jquery-ui tabs, 3 of them contain a table each that is generated by php for the data, with each of them there's a set of input to filter according to the date, each table have their own form and update button. Now what I want to achieve is once I refresh and get back to the controller I want to add the corresponding fragment according to the button I pressed.
For example: If I click on the update button from the first tab I want to add #tabs-1, if it's the second one then I want to add #tabs-2.
Now I know I can do:
$_SERVER['SCRIPT_URI'] = $_SERVER['SCRIPT_URI'] . "#tabs-2";
Fine that gives me the correct url, but how do I make the browser go there at runtime? Is there any way to do this?
Here's a part of my controller, the main one.
class PageOptimisationV2C {
public static function main() {
$class = __CLASS__;
$c = new $class;
$c->get();
}
public function get() {
$this->display();
}
private function display() {
$tpl = new PageOptimisationV2V();
$client = ConsulterClient::getClientByNoClient(isset($_GET['cid']) ? $_GET['cid'] : 0);
$tpl->client = $client;
if(isset($_GET['cid'])){
$tpl->StatsLignesCellulaire = self::buildCellStatsReport();
}
$_SERVER['SCRIPT_URI'] = $_SERVER['SCRIPT_URI'] . "#tabs-2";
$tpl->display();
}
}
And then it goes on and displays the page. What would be the optimal solution to get to a fragment of the page, according to the submit button that is pressed.
I tried to make a jsFiddle to show you how the page looked but it got too messy and couldn't get the CSS to work right.
Every detail of information is appreciated.
The only way i'm aware of to do this with PHP is to do a redirect.
header('Location: ' . $_SERVER['REQUEST_URI'] .'#tabs-2');
This of course will result in another request and require you to do some workaround with your flow but its the only way to send a new url back to the browser.
Though it isn't a runtime PHP method you can also just embed the selection Javascript, for example:
var index = $.index($(<?PHP echo $tab; ?>));
$('#tabs ul').tabs('select', index);
and allow it to go through the normal selection process.
You can also just embed a hidden element, something like
<input type="hidden" name="tab-selected" id="tab-selected" value="tabs-2" />
and have some Javascript to check if the element exists and has a value and then select the tab like this:
$(function() {
if ($('#tab-selected').val()) {
var index = $.index($('#tab-selected').val()));
$('#tabs ul').tabs('select', index);
}
});
Today, with a fresh mind, I thought of something else to do while reading MWJump's answer... Why not use the action attribute of the form! It's there for a reason! So for each of my form (I have one in each of my tabs) I slapped the action attribute to be the fragment of the according tab so for the first tab action="#tabs-1" and the second action="#tabs2" and so on...
I found this solution to be the simplest and easiest in this particular case.

Drupal 7 - how to add another button to a webform?

I was wondering, does anyone know how can I add another button to a webform in Drupal 7 in addition to the submit button? I tried looking through Google as well as asking this question at the Drupal forums, with no luck. Could anyone please help?
Webform is a drupal form and you can use hook_form_alter: Lets say you have a custom module called mymodule and your webform id is 'webform_client_form_XXXXX'. Then use the sample code below.
/**
* Implements hook_form_alter.
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'webform_client_form_XXXXX':
$form['actions']['custom_submit'] = array(
'#type' => 'submit',
'#value' => t('Custom Button'),
'#submit' => array('mymodule_custom_submit'),
);
$form['#validate'][] = 'mymodule_custom_validate';
break;
}
}
/**
* Custom validation handler for your webform.
*/
function mymodule_custom_validate($form, &$form_state) {
// your validation code
}
/**
* Custom submit handler for your form
*/
function mymodule_custom_submit($form, &$form_state) {
// your submit handler code
}
UPDATE:
You would have to substitute instances of mymodule in the above code with yoru modules's name. Also i have modified the hook_form_alter a little. I suggest you move your submit button under $form['actions'], so it would appear next to the current submit button.
To Clear Cache:
visit /admin/config/development/performance and click on Clear all cache button.
To find the weform form-id:
This tutorial on net discuss about how to find the form id. Please note that the id used in the form tag will have '-' (hyphen), that has to be replaced with '_'(underscore) to get the form-id.
Another method is to print the $form_id variable in hook_form_alter ( the function which we have defined above ) and visit the webform page. If there are no other forms on that page the printed id would be the one that correspond to webform. If you enable devel module then it is easier to display debugging information using excellent krumo library.
/**
* Implements hook_form_alter.
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
// Below function would print out the form id in message area if devel module
// is enabled on the site.
dpm($form_id);
switch ($form_id) {
remove dpm( $form_id ); afterwards.
Knowing the webform id is easier than the methods described above. You only need to go to: content->webforms and place the mouse cursor over the edit option belonging to the webform you want the id.
Down the navigator screen the original path in the format node/id will appear. That node number is the XXX in webform_client_form_XXX.
You can use type Markup in webform. Theme the markup as it look a like the button same as your submit button.
and write JS for that. For e.g, you want to give reset button then onclick event should empty the values in those fields. Try this.
first create markup in webform for button then use java script for that when click on this it process request based on your requirement.

Is it possible to force the value of a new CRUD form field?

I am using Agile Toolkit. I have a drop-down field in my CRUD.
How can I make the "New" button display different set of values in this drop-down to when the "Edit" button is clicked?
Here is my code:
class page_things extends Page {
function init(){
parent::init();
$p = $this;
$f = $p->add('Form');
$idCat = ($f->get('idCat')?$f->get('idCat'):$this->api->getConfig('idCat','MASP2U03'));
$dpUE = $f->addField('dropdown', 'Category');
$dpUE->setModel('Category');
$dpUE->js('change',$f->js()->submit());
$dpUE->set($idCat);
$f->addSubmit('OK');
$c = $f->add('CRUD');
$c->setModel('things',array('name', 'field1', 'field2', 'field3'))->setMasterField('idCat',$idCat);
if($f->isSubmitted()){
$c->js(true)->show()->execute()->reload()->execute();
}
}
}
Thank you for help !!
use
$crud=$this->add('CRUD',array('allow_add'=>false));
to disable default Add button, then add your own button:
if($crud->grid)$crud->grid->addButton('Add')->js('click')
->frameURL('Add',$this->api->url('./new'));
After this you'll need to create a new page
class page_things_new extends Page {
and inside this page define the form the way you want it to appear no the "add" click. I don't fully understand your question, but with these instruction you can have a different page appear when adding new entries to your crud.
Here's an alternative to Romans that I've tried. It uses $this->api->memorize to store a GET variable chosen in the drop down list in a session variable. Then in the Form, you can set default the chosen value by using recall in the model.
Something like this
in page/things
// load the javascript function (see later)
$this->js()->_load('your_univ');
/*****************************************************************/
/* Code to populate drop down lists - amend where as required*/
$catList=$this->api->db->dsql()->table('category c')
->field('c.id')
->field('c.name')
->where('c.type',$cat_type)
->order('c.id')
->do_getAssoc();
// Check if one is set on URL or default from config and memorize the value
if ($_GET['cat']){
$cat=$_GET['cat'];
} else {
$cat=$this->api-getConfig('idCat');
}
$this->api->memorize('category',$cat);
$f=$p->add('Form',null,null,array('form_empty'))
->setFormClass('horizontal bottom-padded');
$l1=$f->addField('dropdown','category')->setValueList($catList)->set($cat);
// calls a bit of javascript described later to reload with the parameter
$l1->js('change')->univ()->yourfunc($p->api->getDestinationURL(null), $l1);
.. rest of your page code goes here ..
Then in /lib/Model/Category.php
Add the following recall for the field
$this->addField('idCat')->system(true)->visible(false)
->defaultValue($this->api->recall('category'));
Note the system(true) and visible(False) means it wont show up and wont be changeable on the CRUD but you can play around with the options so it shows in the CRUD grid but not in the form.
Finally, the little bit of javascript to make the reload work (Romans might advise a better way to do this). Make sure yourfunc matches in the page and in the js.
in /templates/js/your_univ.js add the following
$.each({
yourfunc: function(url, name){
document.location.href=url+'&cat='+$(name).val();
},
},$.univ._import);
I've got code similar to this working in my own pages. You can probably make it work as a POST as well as the drop down is a form if you dont want the cat to show on the URL.

Drupal 6: How to hide field-set from being displayed in the form?

I have enabled Location User module and during user registration I am collecting 2 location fields Country and Postal Code. As I am theming user registration form, I want to remove the Location field-set around Country and Postal Code elements.
Could you please guide me?
To alter the location fieldset on content type forms you have to add an after build, like so
function hook_form_alter(&$form, &$form_state, $form_id) {
...
$form['#after_build'][] = 'alter_location_elements';
}
and the callback function would look something like this:
function alter_location_elements($form_element, &$form_state) {
$form_element['locations'][0]['street']['#type'] = 'hidden';
$form_element['locations'][0]['city']['#type'] = 'hidden';
$form_element['locations'][0]['postal_code']['#type'] = 'hidden';
return $form_element;
}
So far no straight answer for this as Location form structure is different from other form array. Basically using drupal_render function, I have populated postal code and country form element outside of the default Location field-set. So template was displaying empty Location field-set.
I rectified it using dirty technique - CSS hack for time being hiding field-set as below:
#user-register fieldset {display:none;}
For D6, the best way (don't use ['#type'] = 'hidden'; or unset(), these methods can produce bugs):
$form_element['locations'][0]['street']['#access'] = false;
In form_alter:
$form['field']['#access'] = false;
By Css:
display:none;
By Js:
$('#IDELEMENT').css('display') == "none"); or $('#IDELEMENT').hide;
It isn't necessary a id element.
If all you want to do is hide the fields from view, then a simple CSS class setting them to display:none; will do the trick.
If you want to actually change the fields that are presented in the form (as opposed to simply hiding them), you can override the fields in a form using the form_alter hook.
The form_alter hook allows you to override the contents of any form. For instance, if you want to add a field to the 'user_login' form, you could write a function like this:
function mymodule_form_user_login_alter(&$form, &$form_state, $form_id) {
$form['myfield'] = array(
'#type' => 'textfield',
'#title' => t('My new field')
);
}
Then when the user login form is displayed, it will now have your new field in it. You can set as many fields as you like in this $form array.
Likewise, you can remove a field from the form by unsetting it as follows:
unset($form['fieldname']);
The problem you will face, however, is that in Drupal 6, the form_alter hook is only available for modules, not themes. So you may need to create a small module to do what you need. I believe this limitation has been removed in Drupal 7.
See the Drupal Hook_Form_Alter documentation for more detail.
You may also want to see this link which is the Drupal bug ticket where they discussed adding the feature to allow form_alter on themes. You'll note that it is marked as fixed with the Drupal version number of 7.
Another option you have for the form is to write your own template for it in your theme. Using this, you can use drupal_render to output each field/fieldset in the form individually. This also allows you to do more complex theming if you want additional HTML code, etc. However, this method is fraught with danger, as if any other fields are added to the form later on, your theme will not be able to cope with it. Its generally not advised to render your form manually in this way.
Hope that helps.

Jquery Load onclick data driven customisation system

This code is to work in combination with a form showing the results of the selections made on the right hand side of the page by loading the URL of the chosen option in a specified DIV that corresponds to the ID of the product.
function product_analysis(productid, address) {
if (this.checked = 'checked') {
$(productid).load(address);
}
else {
$(productid).load('http://www.divethegap.com/update/blank.html');
}
};
Problem is that the query to check if the box is checked or not does not work. If you check or uncheck the box it loads the address of the onclick event.
Any help would be appreciated but please keep in mind that the products are data driven so we cannot have specific IDs but rather IDs built of the Post ID.
Also when the page loads there will need to be some sort of global function which will work out what is 'checked' and load those URLs (products) in their specific DIVs.
Many Thanks,
Beware that you used = instead of == in the if() condition.
Also, have you tried with the :checked selector?
$("#id:checked")
JQuery documentation
function product_analysis(productid, address, box) {
if (box.checked) {
$(#productid).load(address);
}
else {
$(#productid).load('http://www.divethegap.com/update/blank.html');
}
};
and code for the box
onclick="product_analysis('#product_1231', 'http://www.divethegap.com/update/products/2010/11/padi-open-water/', this)"

Categories