Plone: Validate field based on other field's value - plone

Let's say we have a dexterity content type with two fields: field_a and field_b.
In edit mode:
if field_a has the category_1 value selected then field_b is not required
if field_b has other value selected then field_b is required
It seems a simple validation is not possible here. I tried:
from zope.interface import Invalid
def validate_field_b(value):
# value is a string here. I can't create a condition based on field_a.
raise Invalid(_(u"Value in field b is required."))
used here:
field_b = schema.TextLine(
title=_(u"Some field B"),
required=False,
constraint=validate_field_b
)
The result is field_b required all the time. :)
Any solution here? How the get the form / context / request / other fields value in my validator?

The solution is to use an invariant instead of constraint:
https://docs.plone.org/external/plone.app.dexterity/docs/advanced/validators.html#invariants
#invariant
def validate_field_b(data):
if data.field_a != 'category_1' and data.field_b is None:
raise Invalid(_("Missing input for field_b."))

Related

wtforms SelectMultipleField returning only 1 selected value

im following this tutorial to implement a multi checkbox field in flask with jinja
https://gist.github.com/doobeh/4668212
It works for the most part but when I go to access the value in my code (products is the field where I used the multicheckbox) like
class CreateBoardForm(Form):
products = MultiCheckboxField(
'Select Products:',
coerce=int,
choices=[(1, 'one'), (2, 'two'), (3, 'three')])
......
if request.method == 'POST':
products=request.form['products']
print name, description, tags
print "Selected products:", products
When I print selected products I only see one value being selected. When I printed the forms object I see this python data structure ImmutableMultiDict([('products', u'1'), ('products', u'3')])
Im not sure how to get all the values for the 'products' key
you will have to use the getlist method in order to return a list of other choices.
request.form.getlist('products')

Modify query string on a form to add filter based on other fields

I have an enquiry form which works from a view with a custom query. The form has filters, which I use in the executeQuery method of the view on the form to add ranges on various fields.
A new requirement is to filter based on two fields in the query.
Example: The PurchLine table is one of the tables in the query.
A new range is needed :
if PurchLine.ItemId != “” then
filter by PurchLine.PurchStatus == None
but, if the Item has a SPECIFIC value,
then filter by PurchStatus == Received.
(Ok, this is just an example!).
I am unable to modify my query to add a range on the PurchStatus based on the Item field.
I know exactly how the string value of the query must look, but how can I modify the query string?
The current query string looks like this (if I breakpoint on super in executeQuery):
SELECT FIRSTFAST * FROM OpenPOLinesView(OpenPOLinesView) WHERE ((CreatedDateTime<='2016-11-30T23:59:59')) AND ((VendAccount = N'S000001048'))
I want to add this at the end:
AND (((ItemId = N'') AND (PurchStatus = 0)) OR ((ItemId = N'XXX123') AND (PurchStatus = 2)))
How can I modify the query string in code?
You can use query expression for this, e.g.
queryBuildRange.value(strFmt('((%1 == %2) || ((%1 == %3) && (%4 == "%5")))',
fieldStr(InventTable, ItemType),
any2int(ItemType::Service),
any2int(ItemType::Item),
fieldStr(InventTable, ProjCategoryId),
queryValue("Spares")));
Please refer to this link Using Expressions in Query Ranges [AX 2012] for details.

Drupal - How to use Computed field in field collection item fields

I have custom content type type_a
Inside that custom type I have few titles
Title
Body
Group1 (field_group1) (Field Collection Item Can have multiple values)
Following are the details of fields inside Group1 (Field Collection Item)
Group Item 1 (field_item1) Can have one value
Group Item 2 (field_item2) (Computed field) Can have one value
I would like to copy value of "Group Item 1" field of same field collection item inside "Group Item 2"
Below is I am using in computed code:
$entity_field[0]['value'] = $entity->field_item1[LANGUAGE_NONE][0]['value'];
But it is not working. I am getting an error
Notice: Undefined index: value in eval() (line 1 of /homepages/13/d160804/htdocs/test/sites/all/modules/computed_field/computed_field.module(466) : eval()'d code).
Please help how to do this. Thanks
$entity->field_item1[LANGUAGE_NONE][0]['value'] contains the entity id of the field collection item (which contains the fields you want to copy).
You either need to load both field collection items and set their individual fields. Eg,
$source_fc = field_collection_item_load($entity->field_item1[LANGUAGE_NONE][0]['value']);
$dest_fc = field_collection_item_load($entity->field_item2[LANGUAGE_NONE][0]['value']);
// now set values of $dest_fc with values from $source_fc
Or do some sort of clone similar to this method: http://drupal.org/node/1233256#comment-5167316

'Not selected' property value on drop down box selected value

I have an ASP.NET site (either .NET 2.0 or 3.5), and I want to get the selected item of two drop down boxes (call them a and b). B is updated with appropriate values depending on what is selected for A.
However, the following code:
string val = dd1.SelectedItem.Text;
Returns a value of "not selected". Why is this?
Thanks
The only way this could happen is if you have "not selected" set as either the Text property of your selected item, or if Text is null then the Value property will be returned.
From MSDN's documentation on ListItem (which is what SelectedItem inherits from):
If the Text property contains null,
the get accessor returns the value of
the Value property. If the Value
property, in turn, contains null,
String.Empty is returned.

Drupal CCK field select option names, where are they?

I have a custom content type which has a field called "location" which is a long select list (100 or so items). I want to get an array of all locations which have a piece of content associated with them. The numeric value of this field is stored in content_type_[my_content_type], but I can't find anywhere in the database where the name of the values are stored. I hope that's not too confusing - just to be clear, I want to do something like this:
SELECT DISTINCT(field_location_value) FROM content_type_[my_content_type]
and then
SELECT field_location_name_or_something FROM where_on_earth_are_the_names_stored
and then do something with the two arrays to find the names I want.
Can anyone help?
Thanks a lot. Drupal 6, by the way.
If you mean select list field of CCK:
Get all location associated with current node (piece of content?):
$node = node_load('YOUR content ID');
print_r($node->field_location); // $node->field_location - this will array of values.
Get all values of that field (defined in "Allowed values"):
$content_field = content_fields('field_location');
$allowed_values = content_allowed_values($content_field); // array of values
I found this, after much trial and tribulation, in the database table content_node_field_instance, under the field's widget settings field.
This Drupal 6 code snipped will retrieve your cck field value options and put them in the $allowed_values variable as an array. Replace 'YOUR_CCK_FIELD_NAME' with your cck field name (name, not label)
$cck_field_name = 'YOUR_CCK_FIELD_NAME';
$cck_field = db_fetch_object(db_query("SELECT global_settings FROM {content_node_field} WHERE field_name = '%s'", $cck_field_name));
$cck_field_global_settings = unserialize($cck_field->global_settings);
$allowed_values = explode("\r\n", trim($cck_field_global_settings['allowed_values'], "\r\n"));
In Drupal 7 if you have a field of type List (text) then I have written the following function to return an array of options:
function get_drupal_select_options($field_name) {
$options = unserialize(db_query("SELECT c.data
FROM field_config_instance i
INNER JOIN field_config c ON c.id = i.field_id
WHERE i.field_name = :fieldname", array(':fieldname'=>$field_name))->fetchField());
return $options['settings']['allowed_values'];
}

Resources