In my custom content have three fields :
E.g.-
number of = 4
price = $ 2
Sub Total = 4 * 2
How to make the subtotal field as computed field and how to implement it.?
In my custom content have three fields :
E.g.-
number of = 4
price = $ 2
Sub Total = 4 * 2
How to make the subtotal field as computed field and how to implement it.?
I would personal write an event subscriber zope.lifecycleevent.interfaces.IObjectModifiedEvent
doing the math.
https://4.docs.plone.org/external/plone.app.dexterity/docs/advanced/event-handlers.html
In my experience with this problem type, it is a good idea to make design decisions about:
For the at-save-time solution, an event subscriber like Andreas mentions is the way to go — and quite frankly, this is probably the least-complexity, least-coding solution to the problem.
I have implemented computed fields for the on-access using behaviors; for this, there are multiple discussions and examples searchable on this site from previous threads. This typically involves:
plone.restapi
GET
requests this way).plone.app.dexterity.behaviors.metadata.MetadataBase
— in these adapter classes, you don't need to worry about using Zope's ComputedAttribute
and can simply use normal @property
decorators and still get acquisition-related stuff to play nice (which you would not be able to do on a content class without using ComputedAttribute, which is a bit picky about how it is used, and can segfault when used incorrectly).All that said — given the amount of work for the latter solution, if you can use something like an event subscriber for IObjectModifiedEvent
you probably end up writing less code and spending less time getting what you want.
A couple of thoughts:
Slightly related:
You dont always need the field if you just want to 'show it to the users'.
If you make a view for your content type you can put the logic in the view itself.
I use this when field 'A' is a date and 'field B' is a number.
In the view I show 'workdays left', which is a calcualation between 'A' - today - 'holidays'.
Since this changes all the time (and I dont need to 'search for it / have it in the index'), I think it is OK to do this in the view.
If you just want to show the sum, it might even be an option to do the math in a javascript (?)
yes i'm think about that.Where to start
If you add a view with plonecli, it will give you all the logic / code you need
If you do it manually, it would be something like this:
In the view.pt you can get the field for example with
${view/something}
And in view.py
def something(self)
#do the math there
return result
(note the part about 'Available mr.bob templates')
ok let me see
Hi @seanupton
You've mentioned there is a lot of searchable examples for this kind of tasks (on-access field evaluation), what is most detailed and nicely implemented samples? I cant find any