Simple validation through link on API Before Save Script

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cardigansam
    Junior Member
    • Oct 2022
    • 8

    Simple validation through link on API Before Save Script

    I'm looking to forbid a record from being created if a One-side of the one-to-many is too old. I can write code that works in the sandbox, but converting it over to the pre-save script is giving me a run for my money. Right now, I have:

    if (entity\isNew() && workorder.rodate < datetime\addDays(datetime\now(), -30)) {
    recordService\throwBadRequest("Work Order is Too Old!");
    }

    But this simply generates a 500 error when attempting to save a new record on the many-side. Without being able to sandbox it, I'm not sure where it fails.

    The workorder field is housing the related record detail (And you can't via the UI create the recrod without the link being prepopulated, so it'll always be there). the rodate field is simply the date field of the related record.
  • lazovic
    Super Moderator
    • Jan 2022
    • 866

    #2
    Hi cardigansam,

    Please provide error logs of your EspoCRM instance; there should be more information needed to analyze the error.

    Also, check if workorder.rodate is the correct attribute. More about attributes you can find here: https://docs.espocrm.com/administrat...ing/#attribute.

    Comment

    • cardigansam
      Junior Member
      • Oct 2022
      • 8

      #3
      It took a bit to get access to the logs. workorder is the link field and rodate is the field on the linked record. This works in the sandbox, but the error that is recorded to the espolog is:
      CRITICAL: (0) Can't use an entity w/o ID.

      Does this mean that it doesn't recognize the selected record in the link field until it's saved?
      The follow up question makes me unsure so I apologize if this is phrased in a cumbersome way: How would i take the selected record (e.g. workorder field is showing "work order 1" in the unsaved record) and "find that record" to read the rodate field to create the "30 days is too old to create a related record" effect?

      Comment

      • lazovic
        Super Moderator
        • Jan 2022
        • 866

        #4
        cardigansam,

        From documentation: Avoid accessing related records in API Before-Save Script using a dot (e.g. account.assignedUserId). When the script is executed, the relation can be not yet established.

        Comment

        • cardigansam
          Junior Member
          • Oct 2022
          • 8

          #5
          Okay, so that means I have to search for the record to look up the date. But if the link field is unsuable, how do I discover the related record's content? Does the fieldID reference (e.g. workorder.fieldID) still work to use records\findOne based on the record ID or is all reference to the related work order basically off limits pre-save?

          Comment

          Working...