How / When / Where should I use the hidden field? - hidden

I have a dropdown that contain a list of people which contain also a unique id number like for example data1 contain ID = 5. How the ID of 5 pass to the hidden field?.
I'm having trouble understanding on how / where / when to use the hidden field like this
<input type="hidden" id="hidPersonId" />
I'm always asking myself how the hidden field has the value when a scenario is adding a data. How did the hidden field get the value or ID. Please explain to me how did that happen if possible step by step?. Thanks.

hidden fields are made in .cshtml view of the page. Like in your example how did the hidden field get the ID of 5?. After the event of change(choose from the dropdown) the ID is pass to the hidden field. For example
This event is on change function.
var drpSample = $("#drpID").val(); //--- let say the ID is 5
$("#hidPersonId").val(drpSample);

Related

How to access a field name in Django model via the verbose name or Column name

I have the verbose name or column name of a model and I would like to get the corresponding field name. I'm able to access all the field names by using _meta..., but I only want to access a particular field name based on the verbose name.
I would like to plug in the verbose name or column name and get back what the field name is. All the examples that I've found you can only enter the field name in the Model._meta.get_field('fieldname') and not the verbose name to get whatever the field name is.
res = Model._meta.get_field('test_field').verbose_name
res returns 'Test Field'
res = Model._meta.get_field('test_field').name
res returns 'test_field'
If I enter the verbose name for ex:
res = Model._meta.get_field('Test Field').name
I get an error raise FieldDoesNotExist KeyError" 'Test Field'
I would like the output to be the field name 'test_field'
A problem might be here that multiple fields can have the same verbose_name, hence it is not a good identifier. It is not the task of a verbose name to act as an identifier anyway, these are used, as the documentation says to:
A human-readable name for the field. If the verbose name isn't given, Django will automatically create it using the field's attribute name, converting underscores to spaces.
We can make a function that does this, like:
def get_field_from_verbose(meta, verbose_name):
try:
return next(f for f in _meta.get_fields() if f.verbose_name == verbose_name)
except:
raise KeyError(verbose_name)
We can let it work with multiple names of a field, like:
def get_field_from_verbose(meta, verbose_name):
try:
return next(
f for f in _meta.get_fields()
if f.verbose_name in (f.name, f.verbose_name, f.db_column)
)
except:
raise KeyError(verbose_name)
But this even looks more problematic, since now the database column name of one field can be equal to the verbose name of another field, making it even more non-sensical.
and thus call it with:
get_field_from_verbose(Model._meta, 'Test Field')
It will raise a KeyError as well, given no such field can be found.
After a user selects a check box that displays the verbose name I'm using that name to access the fieldname to use in a query.
If this is more the sake of user interface, you should attack the field name as value to the checkbox, and the verbose name as "label". Like for example:
<input type="checkbox" name="sel_fields[]" value="fieldname1">Verbose fieldname 1<br>
<input type="checkbox" name="sel_fields[]" value="fieldname2">Verbose fieldname 2<br>
<input type="checkbox" name="sel_fields[]" value="fieldname3">Verbose fieldname 3<br>
Here the user will thus see Verbose fieldname 1 for the first checkbox, but if the user selects that checkbox, and hits the submit button, the view will receive the fieldname1 value, so the real name of that field.
This is in essence what Django does when you for example use a ModelChoiceField in a form: it presents the items nicely, but behind the curtains, it passes the primary key as value, and thus when one submits the form, we receive the primary key of the selected item back, not the textual representation of that object.
I agree with Willem that there are issues here with reliability and determistic behaviour, but something like this would work:
{field.verbose_name: field for field in model._meta.get_fields()}['Test Field']

Render the FileField as multiple file input field in the form based on multiple choices field

I have 2 models, Product and Document. Document has a FK to Product.
class Document(models.Model):
product = models.ForeignKey(Product, related_name='documents', on_delete=models.CASCADE)
document = models.FileField(upload_to=file_upload_to)
type = models.CharField(max_length=255, choices=DOC_TYPE)
The Document can have different types (data sheet, whitepaper etc).
So, if I have 3 types of documents I want to see in HTML 3 inputs, each input representing a type:
<input name="myFile" type="file"> --> type 1
<input name="myFile" type="file"> --> type 2
<input name="myFile" type="file"> --> type 3
After the form is submitted, I want somehow to know which type of document was it and then, modify the form and select in code the type
I'm thinking on using a custom widget inheriting from File, and add an attribute in each input, and then in save method identify the type
Passing 1) what if I want to let the user add multiple documents for each type, and the number will not be equal for each one of type (a type can have 3, another type 1, and the third one none)
The user will not select the type, he will just upload files, based on UI.
See the example image below, the icons/image are the inputs (behind css done)
Each input represent a choice. In reality is just an input file field per but I create 3 for each choice/type. The user can add as many file per type/choice by click an add (plus sign) near the type/choice icon/image(that is in design)
On your view that creates the formset:
for form in formset:
form.fields['document'].widget.attrs = {'mytype':'whitepaper'}
Then on the POST you capture the attribute to check if that is whitepaper.
Let me know if that works

how to match a field name with another field name

I have two fields that run throughout a website that I would like to match so that when a user inputs a value either of the fields, it will match the other field. I'm using Sitecore Rocks and am trying to use a query to do this.
select ##h1#, ##Title#
from /sitecore/Content/Home//*[##h1# !="##Title#"];
update set ##h1# = ##Title# from /sitecore/Content/Home//*[##Title# = "<id>"];
What am I missing here?
This article talks about tapping in to the item:saving event which allows you to compare the fields values of the item before and after the changes:
http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/11/Intercepting-Item-Updates-with-Sitecore.aspx
Using this, you can determine which field has been amended, then change the other to match.
I've had to do something similar to this when a new field was added, and we wanted to set the initial value equal to an existing field. It may be a bug in Sitecore Rocks, but I found it would only update a field when a static value was part of the query.
When I ran ##h1# = ##Title#, the query analyzer would return the correct number of items updated, but no values were actually updated. However, ##h1# = '<id>' worked perfectly. After trying a number of things, I found this did what I wanted.
update set ##h1# = '' + ##Title# from /sitecore/Content/Home//*[##Title# = "<id>"];
I hope that helps.

Setting a Sitecore Template Field source value as a dynamic Sitecore query

I have a use case in which users need to select a field value from a droplist of items. The problem with this is that the droplist needs to be dynamically built on each item (all with the same template) to only show items in a folder that have a field value equal to that of the current item's ID. In case you're already lost, here's an example of the structure:
- sitecore
- content
- Home
- ContentItem1 (with droplist)
- Site Data
- SelectableItem1(ContentItem1 selected in 'itemid' field)
- SelectableItem2(ContentItem1 selected in 'itemid' field)
- SelectableItem3(ContentItem1 not selected in 'itemid' field)
- SelectableItem4(ContentItem1 not selected in 'itemid' field)
- templates
- ContentItem1Template
- Droplist field (source set to below query)
I want my query to assign the ContentItem1's droplist field source dynamically by getting a list of items that have ContentItem1's id as their 'itemid' field's value, but by comparing the field value to that of the ContentItem1 id. I have tried doing this by comparing the field's value to the id token, like so:
query:/sitecore/content/Site Data/*[##itemid#=$id]
No matter what value I try for id ('$id', $id, #id, '#id', ##id, '##id', etc.) it does not want to resolve on the item level. Is there some way to do this so that I can reuse this ContentItem1Template for all of my items that need the same functionality?
If you are using Sitecore 7 then you can use coded field datasources. This will allow you to use any custom logic you like to specify the items which should appear in your lists.
Create a class that implements IDataSource and the ListQuery() method that returns a list of Items as the source of your field. Then set the source of your field to your method with the code: prefix, e.g. code:MyProject.Custom.FieldDataSource,MyProject.Custom
using System;
using Sitecore.Buckets.FieldTypes;
using Sitecore.Data.Items;
namespace MyProject.Custom
{
public class FieldDataSource : IDataSource
{
public Item[] ListQuery(Item item)
{
var root = item.Database.GetItem("/sitecore/content/my-item");
// some other logic to filter your item set
return root.Children.ToArray();
}
}
}
These articles should help you:
Custom Classes as Data Template Field Sources
Having code as your field its datasource
You may need to wrap the ID in single quotes like so:
query:/sitecore/content/#Site Data#/*[#itemid='$id']
That said, this seems like a good fit for using the Sitecore Link Database. Whenever you associate a SelectableItem to a ContentItem, Sitecore will store that relationship in the Link database (as long as you reference it using a field that supports it, such as a DropLink, DropTree, GeneralLink, etc.).
From there, you can use Globals.LinkDatabase.GetReferrers(contentItem) or contentItem.Links.GetValidLinks() to get a list of all referring items to the content item. This is where you can filter down the list by template ID to ensure that you only return SelectableItems.

Django annotate according to foreign field's attribute

I normally use something like this "Tag.object.annotate(num_post=Count('post')).filter(num_post__gt=2)" to get tags with more than 2 posts. I want to get number of posts with a field value (e.g post.published=True) and annote over them so that I get tags with number of published posts bigger than some value. How would I do that?
Edit:
What I want is not filter over annotated objects. What I want is something like this: Tag.objects.annotate(num_post=Count("posts that have published field set to true!")). What I am trying to learn is, how to put post that have published field set to true in Count function.
You can just replace the 2 in ..._gt=2 with some other variable - for example, a variable that gets passed into the view, or a request.GET value, or similar.
Is that what you're trying to do?