I have two fields in a page that need to be added together to create a total. I am currently adding the field values together in the template, but would like to move this to a controller to keep the template clean. I have added a field method to format currency that I am using with each of the component fields and would like to use that with the total. Is there any way to create a new Field instance in the controller that I can then use in the template so that I can use the Field methods?
You can update the fields like this:
try {
page('pagename'))->update(array(
'title' => get('name'),
'degree' => get('degree'),
'email' => get('email')
));
} catch(Exception $e) {
echo $e->getMessage();
}
If you include a field that doesn’t exist yet, it will be created. If you assign null to an existing field, it will be deleted.
Thanks, that helped. I made a small change since the page is already available in the controller.
try {
$page->update(array(
'title' => get('name'),
'degree' => get('degree'),
'email' => get('email')));
} catch(Exception $e) {
echo $e->getMessage();
}
Top! I only hope you also changed what fields you are updating and with what data.
btw updating field directly with a get() value is really not good, so bad example by my side
Right,
Here is my actual code in case it is helpful to someone.
try {
$page->update(array(
'coa_in_state' => $page->direct_costs_in_state()->int() + $page->indirect_costs_in_state()->int(),
'coa_out_state' => $page->direct_costs_out_state()->int() + $page->indirect_costs_out_state()->int()));
} catch(Exception $e) {
echo $e->getMessage();
}
The more I look at it, the more I’m convinced there should be some simple way to load a page model with additional temporary fields for such solutions. I will add that to my todo list.
That would be nice. In my case above it isn’t a big deal for the total to be added to the content.txt file. But I have another field that I am changing the formatting for display in the controller. It might be nice to be able to add the formatted value to the $page, but I don’t think I would want that formatted value added to content.txt.