Grails - how to hide a date inside a form - forms

I have an 'edit' view for a model that has several fields (one of which is a date). I only want a few of the fields visible to allow edits, so I just hide the other fields using <g:hiddenField>
But one of the fields is of type TimeStamp and I can't seem to find a way to hide this in the form. I tried
<g:form method="post" >
<g:textField name="firstName" value="${applicationUserInstance?.firstName}" />
<g:textField name="lastName" value="${applicationUserInstance?.lastName}" />
<g:datePicker name="createDate" style="visibility:hidden;" precision="day" value="${applicationUserInstance.createDate}" />
The date picker is still visible. Any idea how to hide the date so that I can just pass this to the update method upon submit of the form. Many thanks.

Just re-iterating Rob's comment here. No need to put that on the form. The only data you need on the form is the data you are updating and the ID of what is being updated. Everything else will just stay the same...
def update = {
def applicationUserInstance = User.get(param.id)
// at this point applicationUserInstance.createDate is
// correct.
applicationUserInstance.properties = params
// since no createDate was in the params, it doesn't change.
// so you're good
applicationUserInstance.save(flush:true)
}

Actually my answer below might not be the right answer to your question. Otherwise if you really just have a createdDate-field, which should keep track, when the entry was created in the database, I suggest you do it the Grails-way and use the reserved keywords 'dateCreated' and 'lastUpdated'
Check http://grails.org/doc/1.3.7/guide/5.%20Object%20Relational%20Mapping%20(GORM).html#5.5.1 Events and Auto Timestamping
on how to use these. If you use these then my answer below will be helpful to control the visibility of these fields 'dateCreated', 'lastUpdated'
Suggestions for 'dateCreated', 'lastUpdated'
Probably you want this timestamp to be created automatically as you found it in the Grails documentation but you do not want it to be visible in your view.
Now, to exclude this timestamp from being visible, first
grails install-templates
I assume you have grails-1.3.7
Go to src/templates/scaffolding and check your gsp-files, e.g. 'create' and 'edit'
Search for this line:
<% excludedProps = ["version", "id",
and edit for example 'dateCreated'
<% excludedProps = ["dateCreated", "version", "id",
There is also a tutorial on this topic http://www.ibm.com/developerworks/java/library/j-grails01209/index.html
Greetings,
Jan

Related

2019, Chrome 76, approach to autocomplete off

There are are few posts out there about this. You spend hours going through each answer, testing, reading comments, to find that there is no solution. What have you done in 2019, Chrome 76, that works?
Update, January 2020: It appears that as of Chrome 79, Autocomplete (as defined here) no longer treats autocomplete="some-unrecognised-value" as equal to autocomplete="on", so autocomplete="nope" or similar is now effective at disabling both Autocomplete and Autofill.
Update, April 2020: They changed it again. As of Chrome 81, autocomplete="some-unrecognised-value" is no longer effective at disabling the Autocomplete mechanism. However, Autofill now seems to be a lot more conservative than it was before - it still doesn't follow the spec (a field with name="email" and autocomplete="off" will still receive Autofill suggestions) but it doesn't offer up spurious address fragments on random form fields. My recommendation right now would therefore be to use autocomplete="off". If you want to do that on a field named email, you're probably out of luck though :-(
TL,DR: There appears to be no setting for the autocomplete attribute that will reliably turn off all autocomplete dropdowns. However, the circumstances that have led to this are quite convoluted and worth documenting, to hopefully clear up the masses of conflicting advice...
There are two distinct mechanisms present in current (76.0.3809.132) versions of Chrome, which we'll refer to as Autofill and Autocomplete (not necessarily their official names):
Autofill
The Autofill feature attempts to fill in forms using the address information stored in your browser settings. It can be identified by the "Manage addresses..." option (or similar) at the bottom of the dropdown. This feature does not honour autocomplete="off" or autocomplete="false", as a deliberate decision on the part of the Chrome developers.
In a statement outlining this decision, zkoch offered this workaround:
In cases where you really want to disable autofill, our suggestion at
this point is to utilize the autocomplete attribute to give valid,
semantic meaning to your fields. If we encounter an autocomplete
attribute that we don't recognize, we won't try and fill it.
As an example, if you have an address input field in your CRM tool
that you don't want Chrome to Autofill, you can give it semantic
meaning that makes sense relative to what you're asking for: e.g.
autocomplete="new-user-street-address". If Chrome encounters that, it
won't try and autofill the field.
This is the basis of attempted solutions such as autocomplete="nope"; the Autofill mechanism will skip any fields with autocomplete attribute values it doesn't recognise.
The code that implements this decision, for the record: https://chromium.googlesource.com/chromium/src/+/refs/tags/78.0.3903.1/components/autofill/core/browser/form_structure.cc#1218
Autocomplete
The Autocomplete feature provides a dropdown of previously-submitted values from this form field. This dropdown does not have a "Manage addresses..." option. Autocomplete does honour the autocomplete="off" or autocomplete="false" attribute; any other value (including 'invalid' ones such as autocomplete="nope") will leave it enabled.
Conclusion
Autocompletion dropdowns cannot be turned off through the autocomplete dropdown; any value that disables Autofill will leave Autocomplete enabled, and vice versa. Anyone who thinks they've found a working solution (either through autocomplete or some other method such as CSS hacks) should check that it works against both mechanisms.
Unfortunately it's probably going to be an uphill struggle to convince Chrome's developers that this is broken. The developers of Autofill apparently believe that they made a calculated decision to break autocomplete="off" while offering web developers an alternative; that alternative is broken, for more subtle reasons than they realise. From their perspective, the resulting howls of protest are coming from disgruntled developers too lazy to jump through one little hoop and update their autocomplete="off" attributes. In all the noise, the message isn't getting through: the hoop is broken.
Try using type="search" instead of "text" for your input field, I've done this several time and it works for me.
As of Dec 6, 2019, with Chrome v78.x
Standard methods like autocomplete="off" are now working almost fine for the latest versions of Chrome. Except for this one:
This thing is a real bummer because it doesn't only disrespect the standard/non-standard values like "nope" but there's literally no way to turn this off unless the input is not even remotely related with "addressy" terms.
How on earth we could possibly display address-related input fields without using address-related words? Here comes the easiest solution ever.
Make sure the input element's name and id don't include any address-related terms. Attributes like id="input-street" or name="destination-zip" are big no-no.
This is the most crucial part: If you are required to use any human-readable address terms for the text input or any of its adjacent elements, insert the "invisible" zero width joiner (‌) between the letters of the said term. In this way, we can fool the AI capability of Chrome and bypass its strict autocompletion behavior.
Some working examples:
<input id="input-stret" placeholder="S‌treet" autocomplete="off">
<form action="/action_page.php">
<label for="product-addres">Product A‌ddress</label>
<input name="addres" id="product-addres" autocomplete="off">
</form>
And there you go. No more pesky menus for managing addresses, nor any regular autocompletion menus.
As gasman's answer explains, both the autofill and autocomplete features must be disabled, which doesn't seem possible on a single input.
The only working solution I've found is to setting autocomplete="off" on the input and add hidden fake inputs before the real input that fool autofill, like so:
<input name="Fake_Username" id="Fake_Username" type="text" style="display:none">
<input name="Fake_Password" id="Fake_Password" type="password" style="display:none">
<input name="NameInput" id="NameInput" type="text" autocomplete="off">
* This answer is incorrect. I've published a better (but uglier) solution as a new answer and kept this answer since some parts may still be useful. If that's not how to deal with incorrect answers on stackoverflow, feel free to delete this one *
Consider using autocomplete=<nonce>, where <nonce> is unique per field and across page loads.
For example, if a field is the N-th field created after the page was requested at timestamp TS, its <nonce> can be chosen to be nope_<TS>_<N>.
Effect on autocomplete: since <nonce> is a custom value for autocomplete, chromium does not activate the autocomplete function (see form_structure.cc).
Effect on autofill: chromium recognizes a field by comparing its fingerprint with those of earlier encountered fields (see form_field_data.cc). If recognized it may offer a list of remembered values. The fingerprints contain the value of the autocomplete attribute. Since no two nonces are equal, no field is recognized.
Notes:
The terms autocomplete and autofill as used here are swapped compared to gasman's reply.
All fields should be created dynamically on the client-side (unless you are willing to not have the page cached).
Disabling autofill:
Set autocomplete attribute to a non-standard value, e.g. "nope".
Disabling autocomplete:
The autocomplete function stores field names and their values when a form is submitted.
There's (almost, see note 1) nothing sensible to be done to prevent storage except setting autocomplete to "off"/"false" (see why).
Unfortunately that's not an option as it would enable autofill.
However it's possible to prevent retrieval of previous values by appending "!<nonce>" to the field names, where <nonce> is unique per page load
(thus making field names unrecognizable).
On the client side this can be achieved by something like the following line of javascript (upon page load):
Array.prototype.slice.call(document.body.getElementsByTagName('INPUT'))
.forEach(function(elt) { elt.name += '!' + new Date().getTime(); });
On the server side the part (if any) starting at "!" should be dropped from variable names (upon receiving post variables).
PS: this answer is an erratum to my earlier solution which is cleaner but wasn't sufficiently tested and - as gasman rightly pointed out - doesn't work for ordinary forms. This new solution was tested on Chrome Canary 79, does work, has relatively small impact and degrades nicely. Still, I feel guilty about publishing this hack and will feel even more guilty if I ever encounter it in real forms. It is *very* dirty.
Note 1: the only way to prevent storage that does make sense is to not set the name attribute in the first place (or to unset it), which necessitates intercepting the submit event to post the data "manually" (using XMLHttpRequest). Since the question is about forms and this strategy bypasses the traditional form-mechanism I've not elaborated on that approach. It's a nicer solution though.
Addendum: I decided to follow up on note 1 since I really dislike having a non-localized solution. Here's a localized version in vanilla JS that limits all impact to a single spot on the client side. Append it as a script to the document body or put it in the onload handler of the document.
function disableInputSuggestions(form) { // note: code uses ECMA5 features
// tweak the inputs of form
var inputs = Array.prototype.slice.call(form.getElementsByTagName('INPUT'));
var nonce = Date.now();
inputs.forEach(function(input, i) {
input.autocomplete = 'nope'; // prevent autocomplete
input.originalName = input.name || input.id; // to not let this code break form handling of inputs without names (browsers fallback to the id in that case)
input.name = nonce + '_' + i; // prevent autofill (if you're willing to eliminate all input ids first, then clear the name instead)
});
// replace the default submit handler by a custom one
form.onsubmit = function(ev) {
// get the form data using the original variable names
var formData = new FormData();
inputs.forEach(function(input) { formData.set(input.originalName, input.value); });
// submit the form data using XMLHttpRequest (alternatively, use a helper form or temporarily undo the tweaks to form)
var submitter = new XMLHttpRequest();
submitter.open(form.getAttribute('method'), form.getAttribute('action'));
submitter.onreadystatechange = function() {
if(submitter.readyState == 4 && submitter.status == 200) {
// handle the server response, here assuming the default form.target = "_self"
document.open();
document.write(submitter.responseText);
document.close();
}
}
submitter.send(formData);
return false; // prevent submitting form
};
}
disableInputSuggestions(document.forms.myForm); // assumed: the form has id = myForm
In Chrome 91
You need to use a random value, meaning a value that will change each time you load the page.
From the tests that I did, chrome seems to remember any attribute value that it already encountered and will suggest the last seen value for that attribute value the next time. So, if you put autocomplete="nope", chrome will remember that autocomplete="nope" is equal to the last value that you put in autocomplete="nope".
By using a unique random value that chrome has never seen, it won't suggest anything because it has never seen that value.
PHP 7 Example
<input type="text" name="firstname" autocomplete="<?= bin2hex(random_bytes(10)) ?>" />
Limitations
It seems to work on address fields but it has no effect on login fields. I haven't tested with credit card fields.
Chrome version 81.
For me, when input type is TEL, EMAIL or SEARCH, it WORKS with autocomplete='disabled'.
When input type is NUMBER, it WORKS with autocomplete='off'.
But when input type is TEXT .. it may works with autocomplete='off'. If not, it will do with autocomplete='disabled'.
You can try this, perhaps it will work for you (it works in 95% of cases for me) :
// Désactivation de l'autocomplete des input text
function setAutocomplete(val) {
var E = document.getElementsByTagName('INPUT');
for (var i = 0 ; i < E.length ; i++) {
if (E[i].name == 'txt_nom') { console.log('txt_nom', E[i]); }
var type = E[i].type.toUpperCase();
if (E[i].autocomplete != '') { continue; }
if (type == 'HIDDEN') {
//
} else if (type == 'NUMBER') {
E[i].autocomplete = 'off';
} else if ((type == 'TEL') || (type == 'EMAIL') || (type == 'SEARCH')) {
E[i].autocomplete = 'disabled';
} else {
E[i].autocomplete = val;
}
}
}
// Exécution de diverses fonctions à la fin de chaque chargement
window.addEventListener("load", function() {
// Désactivation de l'autocomplete des input text
setAutocomplete('off');
});
try this, I used this little trick and it worked until now (September 2020). i hope this works for a lot of people
--HTML--
<input type="text" name="example" autocomplete="off">
--Javascript--
let elements = document.querySelectorAll('[autocomplete="off"]');
elements.forEach(element => {
element.setAttribute("readonly", "readonly");
element.style.backgroundColor = "inherit";
setTimeout(() => {
element.removeAttribute("readonly");
}, 500);
})
I made a small jQuery plugin that disables any type of autocomplete feature from any browser
It is made to be used on the form tag, it takes few parameters and can be nested with other jQuery methods.
$('#login_form').randomizeFormFields();
It transforms this:
<form id="login_form" action="" method="post">
<input type="text" name="email">
<input type="password" name="secret">
</form>
Into this:
<form id="login_form" action="" method="post">
<input type="text" name="yQoiFZkCrzwWXN3WWgM8Jblby">
<input type="password" name="ono1qamA9CzrH4tW2COoRtFKI">
</form>
It preserves the original names upon submit
// returned post (php example)
array(2) {
["email"]=>
string(16) "email#domain.com"
["secret"]=>
string(19) "supersecretpassword"
}
https://github.com/cicerogeorge/randomize-form-fields
Please fork it if you have ideas
I have tried with autocomplete = "off" and autocomplete = "nope" for EmailId textbox in html form but it is not working for Google Chrome. So I tried with below changes that worked for me.
<input type="email" class="tbx-input" name="Email" style="display:none;">
<input type="email" class="tbx-input" name="Email" id="Email" placeholder=" " required autocomplete="nope">
I couldnt get any of these suggestions to work... so I just made my input a textarea, made cols="1" and disabled adjusting the space.
<textarea style="resize: none;" type='search' class="form-control" rows="1" cols="50" .... >
No more suggestions
autocomplete='nope'
This is the current working solution for Chrome 76.

How can I pull data in a controller and form for one model that is in a different model with out a foreign key relationship?

I am new to rails and haven't really done to much with data outside of the model.
I have a form that references a table controller for files. I want to add an dropdown that will display a list of projects from a project table for the user to assign a the file to a project if they want too. Assigning a project is not a requirement. The file can be unassigned to a project. I do have a project_id column in the file table for those projects assigned but it is allowed to be null and I did not build a relationship because I need to have cases where there are none.
Can someone please tell me how to do this?
When they evaluate the file, the screen posts back with a save or update button depending if it has already been saved in the database.
At the same time as the save and update pop up on the right I want to display a list box of the projects with an assign project button. If new just a list, if update either just a list because not assigned or display the selected value in the list if already assigned, while allowing them to change it from the list if desired.
In the file controller method that posts back to the UI I have this code:
#file_alias_filedata = FileAliasFiledata.all
#projects = Project.all
for update
#projects = Project.find(params[:id])
In the form I have this code:
<p> <label> Select Project to Assign:</label> <br />
<%= select_tag 'projects', (#projects.present? ? options_for_select(#projects, #selected_project) : []) %> </p>
The form runs but I get this in the dropdown box:
#<Project:0x))7ff531ab4518>
Can someone please help me figure out how to accomplish my task and why I see the strange box value?
What am I doing wrong?
Thank you for your help!
Assigning a project is not a requirement. The file can be unassigned
to a project. I do have a project_id column in the file table for
those projects assigned but it is allowed to be null
From the docs:
belongs_to(name, scope = nil, options = {}) public
Specifies a
one-to-one association with another class. This method should only be
used if this class contains the foreign key. If the other class
contains the foreign key, then you should use has_one instead. See
also ActiveRecord::Associations::ClassMethods’s overview on when to
use has_one and when to use belongs_to.
Methods will be added for retrieval and query for a single associated
object, for which this object holds an id:
association(force_reload = false)
Returns the associated object. nil is returned if none is found.
Likewise,
has_many(name, scope = nil, options = {}, &extension) public
Specifies
a one-to-many association. The following methods for retrieval and
query of collections of associated objects will be added:
collection(force_reload = false) Returns an array of all the
associated objects. An empty array is returned if none are found.
But belongs_to() and has_many() are supposed to make things more convenient for you. You certainly do not have to use them.
Next,
and why I see the strange box value? What am I doing wrong?
You see the strange value for the same reason the following two loops display different things:
class Dog
attr_reader :name
def initialize(name)
#name = name
end
end
#dogs = [
Dog.new("Sam"),
Dog.new("Betty"),
Dog.new("Pete"),
]
#dogs.each {|dog| puts dog}
#dog_names = #dogs.map {|dog| dog.name }
#dog_names.each {|dog_name| puts dog_name}
--output:--
#<Dog:0x0000010099a308>
#<Dog:0x0000010099a2b8>
#<Dog:0x0000010099a268>
Sam
Betty
Pete
You will see the same result if you do something like the following in a view:
<div>
<%= select_tag "dog", options_for_select(#dogs) %>
</div>
<div>
<%= select_tag "dog_name", options_for_select(#dog_names) %>
</div>
If you read the docs here:
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_for_select
...you will see several examples, which should make it clear that options_for_select() takes an argument that is:
An array of Strings.
A Hash where both the keys and values are Strings.
An enumerable that iterates over some Strings.
etc.
Do you see a pattern? It's Strings! options_for_select() needs an argument that consists of Strings. If the argument is not a collection of Strings, e.g. an array of project objects, then options_for_select() tries to convert the objects to strings by calling to_s() on the objects. And the default to_s() method is Object#to_s() which is inherited by all objects and produces a string containing the class name and the object_id.
I am also new to rails, but I think you can try using the options_from_collection_for_select method.
<%= select_tag :search_state, options_from_collection_for_select(State.find(:all, :select => :name), :name, :name) %>
Hope this help. Cause it certainly helped me.

Meteor Handlebars templates: switching from text to input

One part of my meteor application is a semi-collaborative table where users can edit different rows at the same time. When a user is editing a row, the static text values need to switch to input boxes so that the values can be edited and then saved. I would like a template/helper to do this, essentially I want:
<td>
{{#if iAmEditing}}
{{foo}}
{{else}}
<input type="text" name="foo" value="{{foo}}">
</td>
except that there are several columns with different values of "foo" and I don't want to copy and paste this several times. What's the right way to approach this with templates and helpers?
Another approach might be to use the HTML5 contenteditable attribute. Either way, what is the right way to template these values with handlebars?
You should be able to integrate with Bootstrap Editable
For reference, an answer to the original question...
As of today, handlebars partials can't accept anything other than a context argument, but helpers can. Hence. you can define a helper that sets up the context for the template:
Coffeescript:
Handlebars.registerHelper "eventCell", (context, field, editable) ->
return new Handlebars.SafeString(
Template._eventCell
_id: context._id
field: field
value: context[field]
editable: editable
)
Template:
<template name="_eventCell">
<td><div data-ref="{{field}}" class="{{#if editable}}editable{{/if}}">
{{value}}
</div></td>
</template>
Then, I just use the following to render each field:
{{eventCell this "province" iAmEditing}}
I ended up integrating with bootstrap editable, so the template is a little different than my original question. Also, I'm not sure if this is the best way to do it, but it's a lot cleaner than what I had before.
meteor-editable is a new project implementing something like x-editable, but nicely integrated with Meteor reactivity. Unfortunately inline editing is not supported yet (you have to use a popover the way it's set up now).

Commonspot forms hidden field values

I have a form in commonspot, which uses hidden field to pass the information to next form,which it got from a previous form, but I'm not sure about the syntax for the default value of hidden fields. I have tried using form.fieldname, evaluate(form.fieldname), and #form.filedname#.
Can anyone help me with this ?
Thanks,
AA
Ardash - you should paste some actual code to help us understand what you mean.
In general if you want a "default" value (for the case where the item doesn't exist previously) you should use cfparam like so:
<cfparam name="form.myField" default="*some default value*"/>
Then in your hidden field you can safely do this:
<input type="hidden" name="myField" value="<cfoutput>#form.myField#</cfoutput>"/>
Hope this helps. Paste some code for a better response :)
You can list the field names submitted to the page using this method:
<cfoutput>#form.fieldnames#</cfoutput>
alternatively, you can get the field names and data:
<cfdump var="#form#">
This might help you figure out what is going on.

Get/Set Checkbox and Radio Button values using Prototype

Prototype is great, but with the 1.6.1 release, the library still doesn't allow getting/setting of grouped inputs (checkboxes and radio buttons.) I'd like a way to get an array of selected values with $F($("form").checkboxes). I'd like to be able to set those checkboxes to an array of values, on the flip side.
Ideas?
You can always do something like this: (assumes you have your checkboxes have a class of checkboxes).
var checkedList = [];
$$('.checkboxes').each(function(ele){
if( $(ele).checked )
{
checkedList.push($(ele).name);
}
});
edit - just realised i misread the question, code below only good for setting values:
var form = $('options');
checkboxes = form.getInputs('checkbox');
checkboxes.each(function(e){ e.checked = 0 });
// or even checkboxes.invoke('checked',0);
could maybe use something like this though:
var cels = new Array();
$$('checkbox[checked="checked"]').each(el){
cels.push(el.value);
}
This is only for radio buttons, but still useful.
Get
$$('input:checked[name="radio_name"]')[0].value
Set
$$('input[name="radio_name"][value="to_select"]')[0].checked = true
"radio_name" is the name of your radio group. "to_select" is whichever value you want to select. The "[0]" works because only 1 radio button can be checked at a time.
On a side note, I kinda don't like prototype. A lot easier in jQuery, but you gotta use what you gotta use.
I ended up writing my own extensions to Prototype to do this. You can see them on Github. Here's a note from the project:
"These extensions allow you to use Prototype’s convenient $F() syntax to get and set the values of these grouped input elements. They’ve been tested with Prototype 1.6.0.3 and 1.6.1. There are other bits in these extensions as well. See the README.html file for more details."
The answers from seengee and Los are much appreciated, but I wanted a more integrated solution that would allow me to work with checkboxes and radio buttons with the natural $F() syntax that I already use with other form elements.
Given HTML:
<label><input type="radio" id="choiceA" name="choices" value="A" checked="checked" /> A</label>
<label><input type="radio" id="choiceB" name="choices" value="B" /> B</label>
This does a CSS styles query and returns the value for all of the elements.
$$('input:checked[type="radio"][name="group-name"]').pluck("value");