Search code examples
javascriptvisual-studio-lightswitch

Insert DateTime.now() Lightswitch HTML


I am trying to write the current date/time to a field in SQL, data type is DateTime, in Lightswitch HTML.

Basically, when a user saves any edit to a particular screen, I would like for the date and time to be recorded and show on the screen.

In LS, I have a property called DtLastChangedBy. It is the DateTime column in SQL.

I am selecting the AddEditScreen and choosing Write Code > before_applyChanges to modfiy the method.

So far, I have tried things like this...

myapp.AddEditDevice.beforeApplyChanges = function (screen) {
  // Write code here.
  screen.AddEditDevice.DtLastChangeBy
  return Date.now();
};

But I think my js is very lacking =(.

Any suggestions? I will eventually like to return the logged in user as well, so it will show X user last saved this record at X time.

Thank you!


Solution

  • The most elegant approach would be to use the server side 'entity_Created' and 'entities_Updating' methods.

    This ensures that the fields are updated for both client and server generated updates. It also easily accommodates updating a user field (as proposed at the end of your post).

    To implement this approach you'll need to select the 'Write Code' button on your Device table's designer screen and select both of the corresponding 'General Methods' options.

    This will allow you to introduce the following c# code into the 'entity_Created' general method:

    partial void Device_Created()
    {
        this.DtLastChangeBy = DateTime.Now;
        this.UserLastChangeBy = this.Application.User.Name;
    }
    

    And the following into the 'entity_Updating' general method:

    partial void Devices_Updating(Device entity)
    {
        entity.DtLastChangeBy = DateTime.Now;
        entity.UserLastChangeBy = this.Application.User.Name;
    }
    

    In the above snippets I've used the field name 'UserLastChangeBy' to mirror the name you've used for your DateTime field.