Add X days to an existing date field

  • 1
  • Question
  • Updated 2 years ago
  • Answered
  • (Edited)
Hello,

Any JS Superhero who may already have a similar code already made ?

I'm trying to show on a UI only date field (named: NewDate) , a calculation of an existing date field(named: balance_date__c) + result of another UI-only number formula field(named: days_to_add)

So need, balance_date__c + days_to_add = a date in UI field: NewDate

I saw this post , and tried for 1h to modify it to my need, but my noobness is showing lol

Anything close to this scenario, I would appreciate you sharing it,for me to fiddle around with


Thank you
Photo of Dave

Dave

  • 5,538 Points 5k badge 2x thumb

Posted 3 years ago

  • 1
Photo of Thimo

Thimo

  • 1,280 Points 1k badge 2x thumb
Hi we have something similar, that calculates remaining hours in a 48 hour timespan from a created-date.

This is a custom Field Renderer on the createdDate Field.

var field = arguments[0],    
    $ = skuid.$,
    value = arguments[1],
    createdDateTime = new Date(field.row.CreatedDate.substr(0, field.row.CreatedDate.lastIndexOf('.'))),
    currentDateTime = new Date(),
    timeDifferenceInHours = Math.ceil((currentDateTime - createdDateTime) / 1000 / 60 / 60),
    hoursLeft = 48 - timeDifferenceInHours;
if(hoursLeft <= 0) {
    field.element.append('<div class="remaining-box"><span class="remaining-text "> < 60 minutes</span><span class="bid-text animated slideInUp">See!</span></div>');
} else {
    field.element.append('<div class="remaining-box"><span class="remaining-text">' + hoursLeft + ' hours</span><span class="bid-text">See!</span></div>');
}

So I assume that you would have to change the calculation for hoursLeft to balance_date__c + days_to_add while you make this custom field renderer on the balance date field.

So something like this:
var field = arguments[0],    
    $ = skuid.$,
    value = arguments[1],
    createdDateTime = new Date(field.row.balance_date__c.substr(0, field.row. balance_date__c.lastIndexOf('.'))), 
    currentDateTime = skuid.$M('YourUIModel').theRowYouNeed.theFieldYouNeed,
    theTimeYouWant = currentDateTime + createdDateTime;
    field.element.append(theTimeYouWant );
(Edited)
Photo of Dave

Dave

  • 5,538 Points 5k badge 2x thumb
Thank you Thimo,

I tried it but getting errors. I think i'm having issues with that row of code.

currentDateTime =skuid.$M('YourUIModel').theRowYouNeed.theFieldYouNeed,
I tried:
currentDateTime =skuid.$M('accounttest').row.Days_to_add,
currentDateTime =skuid.$M('accounttest').row0.Days_to_add,
currentDateTime =skuid.$M('accounttest').0.Days_to_add,

But page is not loading and i get error: 
Uncaught TypeError: Cannot read property 'Days_to_add' of undefined

As field is from same model as other (not a UI-MODEL) i even tried

    currentDateTime = field.row.Days_to_add,

but now the result date field is showing: "3Invalid Date"

In case it helps I created a testmodel + those fields to show you


<skuidpage unsavedchangeswarning="yes" personalizationmode="server" showsidebar="true" showheader="true">   <models>
      
      
   <model id="accounttest" limit="1" query="true" createrowifnonefound="false" adapter="" type="" sobject="Account">
<fields>
   <field id="Days_to_add" uionly="true" displaytype="FORMULA" readonly="true" returntype="DOUBLE" precision="9" scale="0" label="days to add">
      <formula>1+2</formula>
   </field>
   <field id="new_date" uionly="true" displaytype="DATE" label="New Date"/>
   <field id="LastActivityDate"/>
</fields>
<conditions>
   <condition type="param" value="Id" operator="=" field="Id" enclosevalueinquotes="true" novaluebehavior=""/>
</conditions>
<actions/>
</model>
</models>
   <components>
      <basicfieldeditor showheader="true" showsavecancel="false" showerrorsinline="true" model="accounttest" buttonposition="" uniqueid="sk-2Zjmgi-384" mode="edit" layout="above">
         <columns>
            <column width="100%">
               <sections>
                  <section title="Section A" collapsible="no" showheader="false">
                     <fields>
<field id="LastActivityDate" valuehalign="" type=""/>
<field id="Days_to_add" decimalplaces="" valuehalign="" type=""/>
<field id="new_date" valuehalign="" type="CUSTOM" snippet="dateadd"/>
                        
                     </fields>
                  </section>
               </sections>
            </column>
         </columns>
      </basicfieldeditor>
      
      
   </components>
   <resources>
      <labels/>
      <javascript>
<jsitem location="inlinesnippet" name="dateadd" cachelocation="false">var field = arguments[0],    
    $ = skuid.$,
    value = arguments[1],
    createdDateTime = new Date(field.row.LastActivityDate.substr(0, field.row. LastActivityDate.lastIndexOf('.'))), 
    currentDateTime = skuid.$M('accounttest').row0.Days_to_add,
    theTimeYouWant = currentDateTime + createdDateTime;
    field.element.append(theTimeYouWant );


</jsitem>
</javascript>
      <css/>
   </resources>
   <styles>
      <styleitem type="background" bgtype="none"/>
   </styles>
</skuidpage>


Thank you
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb
Dave,

Try this:

skuid.$M('accounttest').getFirstRow().Days_to_add
Photo of Dave

Dave

  • 5,538 Points 5k badge 2x thumb
ty Matt for syntax, that did remove the error, but this code is still not calculating as it should :(

Instead of getting date I expected (2/29/2016) I get '3Invalid Date'
 it looks like code is getting 'invalid date' for field LastActivityDate 

I wish this could be done in formula fields.. like in salesforce..such a breeze to do simple calculations like those, but unfortunately i need to be able to see calculations in real time (without saving) /rant over/




<skuidpage unsavedchangeswarning="yes" personalizationmode="server" showsidebar="true" showheader="true">   <models>
      
      
   <model id="accounttest" limit="1" query="true" createrowifnonefound="false" adapter="" type="" sobject="Account">
<fields>
   <field id="Days_to_add" uionly="true" displaytype="FORMULA" readonly="true" returntype="DOUBLE" precision="9" scale="0" label="days to add">
      <formula>1+2</formula>
   </field>
   <field id="new_date" uionly="true" displaytype="DATE" label="New Date"/>
   <field id="LastActivityDate"/>
</fields>
<conditions>
   <condition type="param" value="Id" operator="=" field="Id" enclosevalueinquotes="true" novaluebehavior=""/>
</conditions>
<actions/>
</model>
</models>
   <components>
      <basicfieldeditor showheader="true" showsavecancel="false" showerrorsinline="true" model="accounttest" buttonposition="" uniqueid="sk-2Zjmgi-384" mode="edit" layout="above">
         <columns>
            <column width="100%">
               <sections>
                  <section title="Section A" collapsible="no" showheader="false">
                     <fields>
<field id="LastActivityDate" valuehalign="" type=""/>
<field id="Days_to_add" decimalplaces="" valuehalign="" type=""/>
<field id="new_date" valuehalign="" type="CUSTOM" snippet="dateadd"/>
                        
                     </fields>
                  </section>
               </sections>
            </column>
         </columns>
      </basicfieldeditor>
      
      
   </components>
   <resources>
      <labels/>
      <javascript>
<jsitem location="inlinesnippet" name="dateadd" cachelocation="false">var field = arguments[0],    
    $ = skuid.$,
    value = arguments[1],
    createdDateTime = new Date(field.row.LastActivityDate.substr(0, field.row. LastActivityDate.lastIndexOf('.'))), 
    currentDateTime = skuid.$M('accounttest').getFirstRow().Days_to_add
    theTimeYouWant = currentDateTime + createdDateTime;
    field.element.append(theTimeYouWant );


</jsitem>
</javascript>
      <css/>
   </resources>
   <styles>
      <styleitem type="background" bgtype="none"/>
   </styles>
</skuidpage>
Photo of Dave

Dave

  • 5,538 Points 5k badge 2x thumb
I was thinking maybe the problem was the Date conversion from SF to skuid ..

So based myself on other post mentioned earlier

and tried this , but it's prob not in the right syntax, so did not work

var field = arguments[0],        $ = skuid.$,
    value = arguments[1],
    createdDateTime = skuid.time.parseSFDate(skuid.$M('accounttest').getFirstRow().LastActivityDate), 
    currentDateTime = skuid.time.parseSFDate(skuid.$M('accounttest').getFirstRow().Days_to_add);
    theTimeYouWant = (currentDateTime + createdDateTime);
    field.element.append(skuid.time.getSFDate(theTimeYouWant));
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb
Dave,

Is "Days_to_add" a date? If not, you don't want to parse it.

LastActivityDate, is a datetime, not a date, so you want to use skuid.time.parseSFDateTime() for that.
Photo of Dave

Dave

  • 5,538 Points 5k badge 2x thumb
Matt thank you,

As you can see on screenshot above, in my org at least , in account, LastActivityDate is a date field
but still tried it with your suggestion, but got same result , new date is not returning LastActivityDate+3 days (it's returning blank)

And correct, Days_to_add is a number UI only field, so removed the parse, but again same results

At this point i'm a bit at loss, but will continue testing different ways I guess.

Thx
Photo of Dave

Dave

  • 5,538 Points 5k badge 2x thumb
Wow, Actually I just Impressed myself! I completely rewrote that JS and I got it to work, almost perfectly!

The only thing I cannot manage to do, is have the result show in UI only Date field named new_date

I can update field I used originally for calculation but not ui field

var params = arguments[0],   $ = skuid.$;var model = skuid.$M('accounttest');
var row = model.getFirstRow();
var dateVar = row.Month_year_established__c;
var daystoadd = row.Days_to_add;
var newdate = row.new_date;
//convert from Salesforce date to Javascript date
var jsDate = skuid.time.parseSFDate(dateVar);
//add days
jsDate.setDate(jsDate.getDate() + daystoadd);
//convert from Javascript date back to Salesforce date
var daysAdded = skuid.time.getSFDate(jsDate);
model.updateRow(row,{Month_year_established__c : daysAdded});


I tried changing last sentence to : 
model.updateRow(row,{new_date : daysAdded});  but for some reason Ui-field is blank, and do not see any error in console

Is there something i need to add to updateRow because it's a UI-only type of field?


Thx
Photo of Var_GBC

Var_GBC

  • 146 Points 100 badge 2x thumb
Hi Dave, 
 
If UI-Only field set to read only then you can't write it. 
Please make sure read only option is unchecked.

Thx
Photo of Dave

Dave

  • 5,538 Points 5k badge 2x thumb
Hi Var,

Unfortunately that is no the issue. Field does not have it the 'read only' checked.

Thx
Photo of Rob Hatch

Rob Hatch, Official Rep

  • 44,006 Points 20k badge 2x thumb
Question.  When you look at the model values in the console,  is the value changed?  If so - its just that the component is not re-rendering.  If the value in the console is not right its a problem with your code. 
Photo of Dave

Dave

  • 5,538 Points 5k badge 2x thumb
Hi Rob,

I'm ashamed to say that I have no idea how to check in console value for a field. 
Looked in forum to see if was ever explained, but could not find any

If possible, could you please explain me how or point me in right direction? I can see this being very useful for future issues

Thx
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb
Ctrl+Shift+J will open the console (in Chrome, at least).

you can execute whatever javascript you want in the console, and have full access to the skuid API. To find the value of a field I usually do something like this:
skuid.$M('MyModel').getFirstRow();
the console will return the row obeject, and you can expand it to find the value.
You can be even more explicit to just get the value of the specific field:
skuid.$M('MyModel').getFirstRow().My_Field__c;
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb
Additionally, it may be helpful to pepper your code with
console.log(WHATEVER YOU WANT TO LOG);
Then when you can look at the console to see what's going on.
Photo of Dave

Dave

  • 5,538 Points 5k badge 2x thumb
Thank you Rob and Matt,

this is very helpful.

I think i found the issue, as value appears in console , i realized i had assigned the snippet name in the field renderer of the 'New_Date' Field where i expected result.

But if I don't assign it to a field... JS does not apply calculations. Any field I assign this field renderer i can no longer see data from that field...

So not sure what is the recommended way at this point..

Create another UI-Field just to assign it ? 

thx
Photo of David Forder

David Forder

  • 2,154 Points 2k badge 2x thumb
Used this as a bit of a template but doesnt seem to work?

We have a field called "MostRecentContact", another number field for the days interval, "ScheduledContactFrequency"and want the result in a date field "NextDue" - none of the fields are UI fields and none are read only.

The javascript is below.. does anything dramatically wrong jump out at anyone )

var field = arguments[0],
$ = skuid.$,
value = arguments[1],
SourceDate = new Date(field.row.MostRecentContact.substr(0, field.row.MostRecentContact.lastIndexOf('.'))),
DaysToAdd = skuid.$M('Account').getFirstRow().ScheduledContactFrequency,
NextDue = SourceDate + DaysToAdd;
field.element.append(NextDue)

Any help would be greatly appreciated )