Last updated January 28, 2012. Created by venkat-rk on June 4, 2007.
Edited by colan, LeeHunter, cbow. Log in to edit this page.
This is a collection of sample code snippets that can be used in CCK fields enabled by the Computed Field module.
If you have a snippet that performs some new function, please add a new page to this section. If you have a variation on an already documented function (e.g. a different method to achieve broadly the same effect) please add a comment to the relevant page.
Comments
Copy CCK user name field
I am just beginning with Computed Fields, trying to extract and store the first letter of user last names into a second, computed field called alphaBar.
I have a CCK field called field_username_value storing last names strings in a content type table called content_type_nb2.
I have defined a new computed field in content_type_nb2 (field_alphabar_value) which I cannot seem to populate at all.
To break the task down, I am now just trying to copy the contents of field_username_value over into the computed field -- but without success:
Computed Code:
$alphaBar = $node->field_username_value[0]['value'];
$node_field[0]['value'] = $alphaBar;
Display Format:
$display = '>>> ' . $node_field_item['value'] . ' <<<';
All I ever get from this is the empty result string from the $display variable ... ">>> <<<"
Where am I going wrong with my field computation?
not using database stored version, but still getting cached
I have a computed field that is working in the sense of it displays initially correctly. But then I can change the value it is supposed to display, and it seems like it is cached, it does not update on a new viewing of the node. I am not using the database stored version. Using Drupal 6.20, can computed_field 6.x-1.0-beta3
I installed the cacheexclude module to keep the node pages in question from being cached, did not help.
I can clear caches and then it shows the correct value in the computed field.
Now, if I add the same code essentially for computing the field to my php input enabled body field, the php is correctly executed on each node view.
so bug with computed filed beta3? but cannot upgrade to beta4 as it prevents addition of new nodes?
_________________________
Dave Parizek
Land Rover Geek
FYI, this page is referencing
FYI, this page is referencing only Drupal 5.x, and is referred from the main Computed Field page. Someone might want to update that.
I'm trying to grab just the first letter from the login name of the current user, or the node author, and append it to a computed value. I can't seem to locate the proper reference to extract that string. It also doesn't appear that CF utilizes tokens from the Token module. Anyone done anything like this or have any ideas?
Steel Rat
Some of My Drupal Sites:
Helm's Deep RPG Network
RPGMapShare.com
Infinite Realities
Can I programatically cause Computed Field to be updated/stored?
I have a tree of nodes of type "Assembly", linked by noderefs:
Parent Assembly (noderef-->) Child Assembly
The Assembly type has a Computed Field which depends on content in any children. When I edit a child and click save, my PHP snippet also calls node_save(parent_nid) on each parent assembly that it discovers (by searching all Assembly nodes for its noderef).
I can see that node_save(parent_nid) is executing the parent node's Computed Field PHP code, but for some reason that Computed Field is not stored. However, when I visit the parent node's page, click edit, then immediately click save (without changing anything), the Computed Field is properly stored.
What do I need to call from the child's PHP (instead of or in addition to node_save(parent_nid)) to ensure that the parent's Computed Field is stored?
Quote from Moonshine: "If
Quote from Moonshine: "If values that a computed field is using are changing then they are external to the node it's on. If they are values from a secondary node(s) then a hook_nodeapi call to node_save the related computed nodes would trigger re-calculation and retain the benefits of core cck node caching and Views use (if db saved)."
How to check Role?
Hi,
Does anyone know how to do something like this with a php snippet:
if role = x
then print [some_other_field]
else print "user does not have this role!"
Any help much appreciated,
Thanks,
Joe
Print content based on role
Hi Joe,
I've done something similar with an older D5 site I still have running.
I don't remember where I got the code from but it works perfectly for me. Here's what I do.
Remember to use PHP imput format!
At the point where you want the conditional content to appear, enter this:
<?php
global $user;
$approved_roles = array('Subscriber', 'Author'); // substitute these values for the roles you want to show this content to.
if (is_array($user->roles)) {
if (count(array_intersect($user->roles, $approved_roles)) <= 0) {?>
//Your HTML goes here
?>
The logic I'm using above is to allow based on role. You can simply put some negate logic in where you need it to hide based on role.
Hope that helps!
Steel Rat
Some of My Drupal Sites:
Helm's Deep RPG Network
RPGMapShare.com
Infinite Realities
Hi, Thanks very much for the
Hi,
Thanks very much for the code, but I'll have to go another way with this I think. To use Views I need to store the computed field data in the DB which gets generated upon node save. If the users subscription ends I think (and not 100%) that their 'premium' fields will still be visible until they re-edit ans save their node.
So unfortunately this means that the conditional aspect of this wouldnt work as intended? If I were not using Views I could calculate on the fly and this would solve the problem - but I need Views.
So, I have got a module developer to have a look at upgrading the CCK premium fields module from 5.x to 6.x which deals with this problem at the field permissions level - lets hope it works well!
Cheers, Joe
Ah well, it was worth a shot.
Ah well, it was worth a shot. I forgot the two closing braces anyway... :(
Steel Rat
Some of My Drupal Sites:
Helm's Deep RPG Network
RPGMapShare.com
Infinite Realities
Support needed in configuring a "+1 day" commputed field
Hello
I have on my website a node type in which the user can enter the date of a monday, e.g. 4/4/2011. The node then refers to "the week of 4/4/2011", with fields refering to monday, tuesday, etc... Now how can I add a field to this node type that automaticly saves the date of the other six days of the week to six other fields?
So when I have a field "field_datemonday", how I can create a computed field "field_datetuesday" that equals datemonday +1 day, a computed field "field_datewednesday" that equal datemonday + 2 days, etc...?
I would really appreciate the help! Thanks!
I am sure that I have overlooked something.
I have uploaded & activated the module. I have created a CCK field using the computed field type. I have created content on the content type to which I had added the CCK computed field. I do not see the field in that form. Where do I put the code?
cperg
Accelerated Design Inc
I think you have to put the
I think you have to put the code into the field via 'manage fields' rather than on the content create form. Once it is set, it just spits out the result for every page created. It's not unique code per page, but unique per field.
Help computing difference (in days) between two date fields?
I am building a system that tracks the number of days that a semi-trailer has been parked in a parking lot. I have two CCK date fields on the node: field_in_date and field_out_date.
If field_out_date has a value, then I want computed field to compute the difference, in days, between field_in_date and field_out_date ... ELSE
If field_out_date does not have a value (the trailer is still parked in the lot), then I want to have computed field compute the difference, in days, between field_in_date and today's current Drupal date
I don't know how to begin the PHP for this. Please let me know if this is possible, and chum up a snippet if you are feeling generous . . .
Thanks!
"Be the URL"
Our Example - This is code to fill node reference fields
We had a situation where we needed to fill three different reference node CCK fields. The city and county fields were being filled by geo location from openlayer module CCK wkt field type. The nearest city is a manual entry used by the editor of the node. Our situation is that the nearest city and the geo location's city could be the same or they could be different.
We wanted, if they were the same, that the reference would not be duplicated. So if they are the same we just set the node reference for one CCK field to NULL. Of course it might be obvious that we used three field entries that were not node references. The code below uses those three fields and some data base query to locate and provide the values in the reference fields.
We put the code into the Computed Code: field. Nothing is stored from this field directly to the database and the Display Format: We determined that the fields update when the record is merely viewed but the values were not saved. The event of editing the node also did not update the database and did not show the values in the node references. The final event of saving the node did update the database and made the entries more permanent.
Hope that this helps those of you who might need some additional ideas in this area. Thanks to your help - b.coleman (Drupal user name)
$result = db_fetch_array(db_query("SELECT n.nid, title FROM {node} n INNER JOIN {content_type_demographics} d ON n.nid = d.nid WHERE title = '%s' AND field_demographic_state_value = 'Texas' AND field_demographic_type_value = 'City'", $node->field_city[0]['value']));
$node->field_reference_city[0]['nid'] = $result[nid];
$node->field_reference_city[0]['value'] = $result[title];
if ( $node->field_city[0]['value'] != $node->field_nearest_larger_city[0]['value'] ) {
$result = db_fetch_array(db_query("SELECT n.nid, title FROM {node} n INNER JOIN {content_type_demographics} d ON n.nid = d.nid WHERE title = '%s' AND field_demographic_state_value = 'Texas' AND field_demographic_type_value = 'City'", $node->field_nearest_larger_city[0]['value']));
$node->field_reference_nearest_city[0]['nid'] = $result[nid];
$node->field_reference_nearest_city[0]['value'] = $result[title];
}
else {
$node->field_reference_nearest_city[0]['nid'] = NULL;
$node->field_reference_nearest_city[0]['value'] = NULL;
}
$result = db_fetch_array(db_query("SELECT n.nid, title FROM {node} n INNER JOIN {content_type_demographics} d ON n.nid = d.nid WHERE title = '%s' AND field_demographic_state_value = 'Texas' AND field_demographic_type_value = 'County'", $node->field_county[0]['value']));
$node->field_reference_county[0]['nid'] = $result[nid];
$node->field_reference_county[0]['value'] = $result[title];
cperg
Accelerated Design Inc
Hello. Before i've written
Hello. Before i've written this, i've tried dissecting some of the codes in the snippet, however, being so noob at this, i've resorted to seek some help.
I have two content types. The first content type i named "equipment". It contains several fields pertaining to the characteristics of the equipment (i.e. property number, serial number, kind of equipment, date purchased, description of the equipment). Also, i have another content type called "Issue ARE" (acknowledgement reciept of equipment). The content type "Issue ARE" has a node reference to the content type "equipment", but i also want some of the fields of "equipment" be automatically saved in the content type of "Issue ARE". These fields are "field_property_number", "field_serial_number" and "field_date_purchased". The counterpart of these fields in the "Issue ARE" are "field_are_property_number", "field_are_serial_number" and "field_are_date_purchased". I am using Drupal 7.
I am currently looking at computed fields to achieve this, but i cannot seem to do it. Can you please give me an example (even for just one field) as to how can i achieve this? The machine name of both content types are "equipment" and "issue_are". thank you very much!
[D7] Retrieving taxonomy term(s) associated with node?
Hi all, I'm trying to retrieve a list of plain text strings from a node's field_tags using Computed Field.
I tried,
$entity_field[0]['value'] = $entity->field_tags['und'][0]['taxonomy_term']->name;but it doesn't return anything, whereas when I wrote in my node.tpl.php,
print_r ($node->field_tags['und'][0]['taxonomy_term']->name);it returns the first taxonomy term associated with the node (i.e. "fruits").
Can anyone explain to me what I should write in Computed Field to extract this exact string (i.e. "fruits")?
fruits??
Have you tried to use the second computed field entry? The one with $display = ?
Also set, under field management, the display to plain text. Make sure it is not excluded.
I have not tried this as it is related to taxonomy, but I am using the $display variable to provide output into the content of the node in other circumstances. I apologize in advance if it doesn't work.
$display = $node->field_tags['und'][0]['taxonomy_term']->name;cperg
Accelerated Design Inc
Obtaining the sum of fields for a specific user
I am trying to get the sum of a field of all nodes for a specific user. Here is the scenario:
Node has a field called "commission" and I am trying to build a view that will calculate the sum of the commission field in all nodes of a specific user. I am using Views Calc and Computed Field. Views calc will only give a sum of all the commissions in all nodes, showing each node on a line. What I want is to show the sum of each user on each line. So rather than showing every node and it's associated user, I want to show one user on each line, with a sum of all the commissions of all nodes for that user.
Sorry if my description is confusing... Please reply if you have a solution, this problem has halted my project!
sum using db_query in computed field
Hi,
Maybe this is useful:
I have a content type OBRA with two fields (among others):
autor: author of a new OBRA
puntos: points corresponding to the new OBRA
Therefore my SQL database automatically generates 2 tables (can be checked thanks to phpMyAdmin)
- field_data_field_autor (for author)
- field_data_field_puntos (for points)
In order to sum the points for all the different OBRAs created by one specific author, I've dnoe the following (Drupal7):
- Create a new field "puntos_usr" for the content type user (Users » Account settings » Manage fields), as a computed field
- Write the following for the computer field:
$usuario=$entity->uid;
$entity_field[0]['value'] = db_query("SELECT SUM (field_puntos_value) FROM {field_data_field_puntos} natural join {field_data_field_autor} WHERE field_autor_principal_target_id=$usuario")->fetchField();
The first line is just to create a variable with the autor id number (uid).
The second line is the db_query. As I feel more comfortable with SQL than with PHP, the main work is done in the SELECT command. It works adding the values of the field (or column) "field_puntos_value" from a join of tables (one with info about the points and the other with info about the authors), and finally filter (WHERE) to take only the rows corresponding to the user.
The good thing is that you can try different SELECT commands in PHPmyAdmin and, when you get it, you just need to copy in in the computed fileld (be careful with some sintax issues like ading {} for the tables)
I hope it is helpful, I've spent several hours to find out this and, thaks to different info in these forums, I got it.
rely to a other field
Hi all,
I am using computed fields with Drupal 7, and have several computed fields dependent to the previous field. For example :
1) the input field
2) computed_filed_1
3) computed_filed_2
And the value of computed_filed_1 is generated from input_field, which work well.
But I have to compute the computed_filed_2 from computed_filed_1.
If I don't get the instruction wrong, the computed field module couldn't do that. This is quite useful and might be common need to most people. Can anyone give me a hint? So far I can think of methods as follows:
1) declare the computed_field_1 and leave it blank, then update computed_filed_1 and computed_filed_2 in the implementation of computed_filed_2. In this way we would actually calculate once. I tried, but it seemed that it is not possible to update other field in this way.
2) force a recalculate after saving the post. but no idea how to do it.
Thanks in advance.
It is not nessasary to have the computed field store values
Would it be possible for you to place additional CCK fields of the type you would want to store. Take one computed field and then use it to calcualte all of the values needed and place them in the additional fields I suggested earlier? This would give the intermediate value you are needing for the calculation of the second result within the same code.
CCK field Item1
CCK field Item2
CCK field SubTotal
CCK field Total
Computed Field Compute-Fields has no stored value! It does have code that calculates the values from Item1 plus Item2 and places that value in SubTotal. Then it takes the value which is still in code and calculates 125% of SubTotal and puts it into Total.
I think doing it the way you have been trying makes the intermediate value unavailable until after the node has been saved. I bet if you edited the node a second time and made a small change that would not affect the computed field it would calculate the second field as you have it described currently.
cperg
Accelerated Design Inc
Thank you. It works, but..
Thank you, cperg. It solves the problem.
But there comes a minor problem to my specific case.I do it this way as you suggest:
1) input field 1
2) input field 2 (which store the value computed_field_1 in my original case)
3) computed_field_2
In the implementation of computed_field_2, I will update the input_field_2, and then update computed_field_2.
But there comes a minor problem, the input_field_2 should be always generated from input field 1. If I implement it this way, the author (any authenticated user can post content) can later modify the input_field_2 manually.
(Unless there is some module which can turn some field off to the author?).But anyway, you help me out of the most critical part of the problem. Really appreciate that.
Update: According to this post http://drupal.org/node/257431#comment-2057358
If I turn off the permission for the input field 2 to the author, computed fields won't be able to update as well.
What I need is one more step here, use hook_form_alter() to hide the field from author.
Hope the two steps would be useful to other people as well.
Just had an idea
Not sure how you actually finished this issue but I just had an idea. Even if the author changed the value in field two and saved the form the calculated values would be re-processed when he hit the save button. Any changes the author made to the form at that place would be over written by the computed field.
A simple note explaining that no changes will be saved from entries would suffice to prevent the average person from changing the values, however some people will try, alas they will have no luck so they would just give up after a time. I think the documentation on the form should be clear enough to prevent too many users from being frustrated when they try to change a field and did not succeed.
cperg
Accelerated Design Inc
Can I pull the user profile when publishing a post?
I am using computed fields on a content type. I want to check the user profile to generate the value for the computed field. But I can't find a way to pull the user profile at this point. I am using
Drupal 7
Computed Field
profile 2
Address field
Any thought would be appreciated?
I saw the age calculation code, but it seemed that the birthday data is saved in a field within the same content type, different from my case.
problem solved
refer to http://drupal.org/node/1087368
similar to following code except that it is for D6
$node_field[0]['value'] = db_result(db_query("SELECT field_phonenumber_value FROM content_type_content_enrollment_application WHERE nid=%d",$node->field_application[0][nid]));How to do this in Drupal 7
Hello.
How can this be written in drupal 7?.. thank you :)...
user preference for a node
Is it possible to display a computed field that shows three let's particular values when the node is edited, but the value selected will be linked with the user that has selected it. Therefore, the value that is selected will be displayed only to the user that has selected it. (Each user can select a value from the three-values-set.)
user preference?
Perhaps storing an array in the computed field with the display portion of the computed field showing the selected element for the global user for the session?
I would believe that the array would be a coupled pair of element value associated with the global user id.
A session that has the node open for a global user for the first time should require the value to be entered. A session for the node being opened with a global user that had been there before could allow changes or not depending on the application.
Hope this idea helps.
cperg
Accelerated Design Inc
how to get term tid?
I want to get the number of nodes that have a term reference to the current term:
$tid = 1;
$entity_field[0]['value'] = db_query("
SELECT count(*)
FROM node n INNER JOIN taxonomy_index t on n.nid = t.nid
WHERE n.type = 'discussion'
and n.status = 1
and t.tid=$tid")->fetchField();
How can I get the tid of the term? Is there a better way of writing the query?
Paid Job to configure quote form
Hi I am looking for someone with experience with this module to write a custom script for a website I am working on.
Fairly straight forward I think.
It is for a manufacturer of storage shelving and will have a few drop down boxes for set height and width measurements then five other fields for entering options all of which have an affect on the final quote figure. The various figures that the module uses to calculate the quote will need to be drawn from CCK fields so the client can update those figures as they change.
I have an excel doc with all the formulas in it for you to help with the quote but will send that after contact is made.
Please send an email to me if you are interested. andrew@creativeconcepts.com.au
There are only 10 types of people in this world. Those who understand binary and those who don't.
Setting a computed field to the value of another field
Hi All,
I hope I am posting in the right place. I am fairly new to Drupal and not versed in php at all yet. I have a field collection with a computed field in it that I would like to have set to the same value as another field in the parent form. The field in the parent form is a single checkbox. In other words when the user checks the box I would like to have the computed field reflect that setting (either as "1" or "yes" or "on"... whatever it really doesn't matter). I would really appreciate help with how to code this. I tried a few things based off the code snippets found here but no luck yet.
Thanks in advance.
:Dee
Look at node reference
In my understanding of the project; you want a field of one node to affect the field of another node. Not sure how each of these nodes are being created but I would think that you would need to reference the "setting node" from the "receiving node" (IOW you will need a node reference field in the "receiving node"). If more than one node could receive the value from the "setting node" the node reference field could be using a view that shows (filters) the "setting node" content type only. If only one can be referenced, another field in the "setting node" such as has "already been used" could provide an additional filter for that same view and prevent multiple "receiving nodes" from using the the same "setting node".
In either case the code becomes more academic when you know the node id of the "setting node" and the computed field would use that value located in the node reference field of the "receiving node" to locate and update a supposed "already used" field and grab the value in the "setting nodes" setting field and place that (or another calculated value based on that) in the appropriate field in the "receiving field".
I hope this helps.
cperg
Accelerated Design Inc
Help with node reference field
Thanks for your reply cperg.
I looked at the available field types for my node and "node reference" was not one of the types. Forgive my noob question but how can I get this node reference field added to my "receiving node".
Thanks,
:Dee
EDIT:
Installed references module. Hopefully this will provide the functionality I need.
Formatting dates in a computed field
I am new to Drupal, so please excuse my ignorance.
I have a computed that consists of education information about an individual. The line I am having trouble with consists of the degree achieved as well as the month and year that the degree was completed. This is what I am aiming for:
Bachelor of Science in Marketing; September 2010
I have set the input settings so that it only asks for the month and year, however, when the computed field is displayed, it is displaying the full date:
Bachelor of Science in Marketing; 2010-09-01 00:00:00
I have figured out how to display the date the way I want on its own, but I have been trying on and off for a couple of days now to format it properly in a computed field with no luck. Is there a way for format the date?
Any help would be greatly appreciated.
duration from a date field with to and from values
this patch is great for entering the to and from and only having to enter a time to specify duration, but doesn't really address how to display that duration (that I can see). change field_your_datetime of course to your actual date field's name.
$from = strtotime($node->field_your_datetime['0']['value2']);$to = strtotime($node->field_your_datetime['0']['value']);
// this is GMT with no lead zeros, so it looks like 1:30 for something an hour and a half long
$duration = gmdate('g:i',($from-$to));
$node_field[0]['value'] = $duration
need help on computed field code
I am using the following code to insert a view aggregated SUM value in to a computed field
code:
$view_result = views_get_view_result('erp_exp_view');
$total=0;
drupal_set_message(serialize($view_result));
foreach($view_result as $item){
$node =node_load($item->nid);
$total=$item->nid;
}
$entity_field[0]['value'] ="$total";
i am getting the following message and error:
Drupal message:"field_field_exp_duration";a:1:{i:0;a:2:{s:8:"rendered";a:2:{s:7:"#markup";s:1:"5";s:7:"#access";b:1;}s:3:"raw";a:1:{s:5:"value";s:1:"5";}}}}}
Notice: Undefined property: stdClass::$nid in eval() (line 5 of E:\wamp\www\sites\all\modules\computed_field\computed_field.module(439) : eval()'d code).
can some one correct this please I wanted the $total value " 5"
Contents of a field to be displayed in another field
Hello,
I am new in Drupal an PHP and I need a little bit help. I want to show the contend of the "Music" in another fields. The field "Music" is a field-list with a select-box.
The field has e.g. following parameters:
######################################
LABEL: Music
NAME: field_music
FIELD: List (text)
WIDGET: Check boxes / radio buttons
In the following list of terms are included:
rock
pop
Classik
soul
jazz
This looks in the Computed Field with me once that way.
Computed code (PHP)
$ entity_field [0] ['value'] = "";
Display code (PHP)
$ = $ display_output entity_field_item ['value'];
#######################################
When I change the parameter in this way :
Computed code (PHP)
$entity_field[0]['value'] = $entity->field_music['Music'][0]['value'];
Display code (PHP)
$display_output = $entity->field_music['Music'][0]['value']
I have the follow error:
Notice: Undefined property: Profile::$field_music in eval() (line 1 of /...../all/modules/computed_field/computed_field.module(465) : eval()'d code).Please can anybody help me!
Thanks a lot ...
HTML output in field
When I put in something like this:
$display_output = "<b>Hello</b>";I want the output to be,
Hello
but instead it comes out as,
<b>Hello</b>
I'm sure it's something very simple, what am I doing wrong?
Nevermind, I was thinking
Nevermind, I was thinking there was something wrong with my code when all I had to do was change the format in "Manage Display".
Computing multiple fields determined by node reference
I am looking for someone who can write what I need to achieve the following:
One content type with a "Total Quantity" field and multiple node references to a second content type.
A second content type with a reverse node reference back to the first content type as well as a field for sub total quantity.
I would like the "Total Quantity" to calculate the values from the sub total fields of all the second content posts which have node relationships to the first.
Anyone able to help me with this?
D7 way to compute SHA1 for a FileField?
I've been struggling to adapt this simple example to D7:
$node_field[0]['value'] = md5_file($node->field_file[0][filepath]);. FileFields seem to only be available upon first upload (if a node is edited, they're not there), and the whole structure for accessing them is unclear to me, even though I've spent several hours toying around with php xdebug and the drupal devel module. Any ideas? Thanks!!Custom User Fields
Drupal 7 HELP PLEASE!!!
I have a couple custom user fields (department and phone) which are mapped to the LDAP module. This is working properly.
I have a custom content type that has a contact field which is a user reference field. This is working correctly.
Now, I want to create a couple calculated fields (department and phone) in this custom content type. I want these fields filled in with the department and phone of the user of the user reference field.
Solution-
edit computed field and in the computed code section:
$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_user_reference')));then in the display section:
$test = db_query("SELECT field_department_value FROM {field_data_field_department} where entity_id = {$entity_field_item['value']}")->fetchField();$display_output = $test;
Calculate from different content types
Hello,
I have a table (content type) called members.
I have a second table (content type) called activities
The activities table contains a "node reference" to the members [field_activiteit_deelnemers] where I can flag the members that where present.
Now, I want to create a computed fiels in the members table [field_leden_aantal_ritten] that counts the amount af activities where the member was present.
It is the first time i want to use the computed field module, but it's not the clear for me.
Thanks for your help !!
Sven
Kind regards
Sven
Store Calculation Results in Database for Future Reporting?
Hello,
I'm not sure whether this module can do this, so I figured I'd ask. I have a few fairly simply calculations which are adding and/or multiplying decimal fields to display a total amount on the page. Those decimal fields will be updated fairly often (probably weekly, but possibly daily), thus updating the calculated field on the live site.
I'd like for each of those updates to be available via reporting (probably via Views) so that we can have an audit trail of what was updated, when, and what the update was.
Is this possible with this module?
Thanks!
Another thought... Is it
Another thought...
Is it possible to add new computed fields on the fly? For instance, if I was tracking gas mileage, I'd want a "miles driven" field. I would want that field to be repeatable when I am editing the content item, so that when I have a new value, I can simply add the new field under the previous field, and have them both then listed on the page (or available for calculation in an overall miles driven calculated result).
field rules module can create any field on the fly
You can try this field rules
I don't think that's exactly
I don't think that's exactly what I need...
I have a a fleet of cars for which I am tracking the total miles driven. Each car is a separate content item. I have an integer field in each of those Car content items called "Miles Driven", and the field is set to be "unlimited", so the user can add new "Miles Driven" as needed. Then, I have a computed field that should simply add up those "Miles Driven" field entries for that car. There could be two "Miles Driven" entries, or there could be 100... it all depends on how often that car is driven.
Can anyone provide me with a snippet that would have some sort of wildcard aspect that would automatically pull in all entries for that "Miles Driven" field for that car content item?
I would be willing to pay for assistance to achieve this functionality if it is something that would require more than just a quick snippet of code.
Thanks!
UPDATEI found a solution for
UPDATE
I found a solution for my mileage calculation:
$field_items = field_get_items($entity_type, $entity, 'field_mileage');
$total = 0;
foreach ($field_items as $item) {
$total += $item['value'];
}
$entity_field[0]['value'] = $total;
I had to change direction a
I had to change direction a bit, and am hoping someone can point me in the right direction...
My content structure is like this:
Content Type: Engine
Field: Total Usage (Miles) - calculated field
Field: Total Usage (Hours) - calculated field
Content Type: Engine Usage Instance
Field: Total Miles Driven since Last Usage Instance - field used for calculation
Field: Total Hours Driven since Last Usage Instance - field used for calculation
On the page for EngineABC123 (for instance), I need to display the sum of the Miles/Hours in the Total Usage (Miles/Hours) fields. I will have many "Engine Usage Instance" content items related to EngineABC123 (via the D7 Reference module), and those are what need to be summed.
Is this possible? If so, can someone explain how to achieve this?
count number of times that product is addet to cart or sold
Hello i just wanted to as if can i count the number of times that a product is addet in cart or sold ?
in Drupal 7
I wrote a super easy guide for beginners to computed_field.module.
Calculate Field Values Using Computed Field in Drupal 7
Here's the code:
<?php/**
* Computed field : field_contest_total_prize
*
* The variables available to your code include:
* &$entity_field, $entity_type, $entity, $field, $instance, $langcode, and $items.
* To set the value of the field, set $entity_field[0]['value'].
* For multi-value computed fields continue with $entity_field[1]['value'].
* Here's a simple example which sets the computed field's value to the value of the sum of the number
* $entity_field[0]['value'] =
* array_pop(array_pop(field_get_items($entity_type, $entity, 'field_a'))) +
* array_pop(array_pop(field_get_items($entity_type, $entity, 'field_b')));
* The first pop fetches the last (or only) item from the field while the second pop fetches its
* ['value'] contents (assuming it's the only key that's set).
*/
function computed_field_field_total_prize_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items){
$entity_field[0]['value'] =
$entity->field_first_prize_cash['und'][0]['value'] +
$entity->field_second_prize_cash['und'][0]['value'] +
$entity->field_third_prize_cash['und'][0]['value'];
}
?>
miss-hana.com | @hanamizuki
Ubercart price with tax
Hey.
Does someone know how to get the ubercart product price, and make the computed field calculate 25% tax on.
Views can only sort prices without tax, because the price with tax is not stored on the database.
So i want the view to sort via the computed field.
Compute amounts from a field in Field collection
Since field collection values aren't stored in the node, only the reference is there, the way to get the values is a bit different than getting them from fields that aren't field collection fields.
In my case I have a field_amount as a field collection field, with unlimited number of values, and wanted to sum them all up:
<?php
$field_items = field_get_items($entity_type, $entity, 'field_items');
$total = 0;
foreach ($field_items as $item) {
$id = $item['value'];
$query = db_select('field_data_field_amount','a');
$query->fields('a',array('field_amount_value'))
->condition('bundle','field_items')
->condition('entity_id',$id);
$result = $query->execute()->fetchField();
$total = $total + $result;
}
$entity_field[0]['value'] = $total;
?>
There may be a way to do it through field collection API instead directly from db.
I have a specific calculation
I have a specific calculation that works in a Global PHP field in a view, and I need it to be "translated" so that it works with a Computed Field CCK field. Here is the code... can anyone shed some light on how to make it work in a Computed Field?
print $data->_field_data['nid']['entity']->field_engine_cycles_at_delivery['und'][0]['value'] +$data->field_field_include_utilization_engine[0]['rendered']['#view']->result[0]->field_data_field_engine_utilization_cycles_field_engine_util;
Its purpose is to add up a bunch of utilization entity fields (total cycles used) and then add that to the total number of cycles that the engine had on it when it was acquired.
Thanks!