Skip Navigation

[Resolved] Where to write code to add 2 fields together

This support ticket is created 3 years, 9 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 -
- 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 -

Supporter timezone: Europe/London (GMT+00:00)

This topic contains 10 replies, has 2 voices.

Last updated by jeremyA-4 3 years, 7 months ago.

Assigned support staff: Nigel.

Author
Posts
#1198552

I'm just trying to work out how to add number fields together. I have looked at thge documentation but I was wondering if somenoe could just give me an example of how this is supposed to be coded as I am reading about all sort sof situations. Is it that complex to add "Field 3 = Field 1 + Field 2"?

#1198658

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

You would typically write a custom shortcode for this, which gets the values of the fields you want to add together, and then returns the calculated result.

You could use a general purpose shortcode to perform calculations, such as this one:

/**
 * Add custom shortcode to perform calculations with Types fields
 * 
 * attribute 'round' for decimal places, defaults to zero
 */
add_shortcode('calculate', function( $atts = [], $content=null ) {

	$atts = shortcode_atts([ 'round' => 0 ], $atts );

	$content = strip_tags( wpv_do_shortcode($content) );
	$content = eval("return $content;");
	return round($content, $atts['round']);
});

You can add that code at Toolset > Settings > Custom Code.

You could then use it in a template where Types number fields were available like so:

[calculate round=2][types field="weight"]*[types field="unit-price"]/100[/calculate]

In your case inside the calculate shortcode you would be doing a simple sum with two or more Types fields.

Do you want to try that?

#1210149

Hi Nigel

Thanks for your response and I apologise for mine being a little delayed!

So I understand this, would I be right in assuming:

Line 6) I am declaring a new shortcode called "Calculate" and then resetting any settings that may be applied
Line 8) Declaring a variable called "atts" (For attributes I'm also assuming) of which I am rounding the decimal places to "0" decimal places....I don't have a clue why the 2nd ", $atts" is there
Line 10) Zeroing the tags although I'm not sure why
Line 11) $content has somehow got the values of my 2 fields and this line is to calculate them
Line 12) Show the answer

I'm completely lost. I may be trying to approach this incorrectly.

I'm used to a language that if I needed to calculate someone's income I would write it like:
1) Lookup the ID of "Person X" and call it "z"
2) From the "Income" table, search for "z" and fetch the associated "Salary" field value and call it "x"
3) From the "Real Estate" table, search for "z" and fetch the associated "Rental Income" field value and call it "p"
4) In the current table, the field "Total Income" = "x" + "p"

Can I relate any of that to the way I need to think for WP or Toolset?

JA.

#1210556

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Shortcodes are a WordPress feature to enable you to run some PHP code when parsing the content to be displayed.

You could create a custom shortcode where the functionality was hardcoded. It could look up the value of the field1 for the current post and look up the value of field2 for the current post, add them together, and then return the result.

But then you could only use it in one scenario. So maybe you would make a slightly more flexible version where you passed the field names as shortcode attributes so that somewhere else you could add field3 and field4 instead.

But then you decide you want to be able to take away one field from another somewhere else, so you update the shortcode again and this time you also pass the operator as an attribute.

Etc.

The shortcode I suggested is a general purpose shortcode for calculations that may or may not include Types fields, e.g.

[calculate round=8]67/19[/calculate]   // 67/18 shown to 8 decimal places

[calculate][types field="field1"][/types] + [types field="field2"][/types][/calculate] // add field1 + field2, show to default of zero decimal places

If you want to better understand the code see the following guide to WordPress shortcodes: https://developer.wordpress.org/plugins/shortcodes/

In the above calculate shortcode, strip_tags is used to ensure no malicious code makes it to the eval function.

#1212221

Thanks Nigel.

Where do I write this code if I want it triggered by an event like say, when a date is changed and I need to change the dates in a series of tasks in a tasklist? If I want it applied to one table only? Is there sometihnhg within a Toolset "Post Type" I can write the code in for that Post Type?

#1212501

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

The shortcode I described above is simply for presentation.

If you are displaying a post and that post has a custom field A and a custom field B with existing values, when you display the post you could display fields A and B and also—with that shortcode—output A + B, without having to store the result of A + B.

Your last comment seems to be describing something rather different.

Rather than speaking hypothetically, is that the actual problem you have in mind?

You have a task post type. It has some date-based fields (e.g. 'start date' and 'due date').

If some other date is changed (what date? Where and how is it changed?) you want to update the start date and due date fields of the task (i.e. re-save the task post with different values for start date and due date).

Can you give me a concrete example of what you are trying to achieve and I can give you an explicit answer.

#1222171
Capture.PNG
Capt1ure.PNG

Hi Nigel

I'm translating a system I have already created in Zoho Creator into WP. With Creator, I simply drag and drop to create a form, then if I want to fetch data or trigger events, I write the code to apply to the table or field in a section for that table or field.I have attached an example of what I am trying to achieve. Now, there is code written in a section that says, "When the status is chnaged to COMPLETE, make the END DATE today then change all the SUCCESSOR task START DATES and END DATES accordingly".

I've just noticed that it cut a few columns out so I included another system I'm playing with also which shows the SUCCESSORS. What a SUCCESSOR is, is a TASK that is to start when the current task is completed..ie: The 1st TASKs SUCCESSORS are "ORDER NEW STRUCTURE FROM ACCOUNTANT" and "CANVAS FILING SET UP", this means that these tasks START DATES will coincide with the current tasks END DATES. The END DATEs are simply the START DATE + DURATION so when the END DATE of anything changes, so to do all of the dates that are to follow the current task and so on and so forth with the system checking to make sure the START DATES and END DATES are recalculated.

So, my exact question is twofold really:

a) How do I achieve the above?
b) Where does the code go?

This is really hard to do without being able to speak to someone....frustrating.

#1222352

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Screenshot 2019-03-28 at 11.17.22.png

The first consideration is how to structure the data, where we immediately run into a problem.

Types relationships don't support self joins, meaning you can connect posts of different types (ingredients to recipes), but not to posts of the same type.

You want to chain together tasks, so you have some tasks, and other tasks that are dependent on those tasks, and more tasks that are dependent on some of these sub-tasks etc.

You can't create such dependencies with Toolset relationships.

For custom post types you can use the built-in hierarchical option, so that posts (of some type) can have child posts (of the same type), which can have their own child posts.

The UI for setting a parent task in the backend could get out of hand pretty quickly, but if you are using Toolset Forms to submit tasks then the select2 library is used which makes it more manageable to search for the task to assign as a parent (see screenshot).

But, a key limitation of hierarchical posts is you can only have one parent, so any given task can only be dependent on one other task.

Before going any further we had better establish if such a limitation is acceptable, because if not we have hit a dead end already.

#1223300
Capture.PNG

Nice Nigel. The first bit of sense anyone has made to me with any system I have been researching, so "Thank You"!

I hit a similar wall with Creator. The way I worked around it was to "Trick" it in a sense by having a table in between as I couldnt have a table "Lookup" itself so created a separate table that was only made up of a lookup field and made that table a subtable of the Task table. ie:

TASKS TABLE ====> TASKS LOOKUP TABLE ======> TASKS TABLE

If you see the attached, the TASKS LOOKUP TABLE (SUCCESSORS) was simply a lookup field that looked up TASKS then was made a subtable of the TASKS table.

Is something like this possible with Toolset and if so, possible without coding?

#1223819

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Well, you could do something similar and create an intermediary post type to act as a bridge between posts of the same type so that you could emulate self-joins.

So, sticking with tasks, you could make a "dependency" post type, say, and whenever a task depends on another task you connect them via a dependency post.

Task A          Task C
    \             /
     \           /
      \         /
    C depends on A

Task B          Task C
    \             /
     \           /
      \         /
    C depends on B

Here you have task C depending on both task A and task B, which wouldn't otherwise be possible, but then the workflow starts to get a little awkward, because you need a form to publish the dependency with selectors for the left and right sides.

Then if you want to display tasks that are dependent on task A you actually create a query for the dependency posts but for each resulting dependency post you output fields from the relevant parent task.

I'm not sure if that helps you or not, depending on exactly how you are gathering and presenting this data.

#1226729

My issue is resolved now. Thank you!