How do I show the logged in user on a Form

I have a form that automatically fills in the “Added By” field but I want to show the logged in user on the form before they submit it. Can someone help me with this?

Hey @Brian1

Not sure why you’d need to do this as the logged in user is shown at the top of the screen? There is no native way to show this when adding a record.
Likely possible with JavaScript but I’m not a coder :man_shrugging:

@Brian1

Carl is correct — you can use JavaScript.

Inside the Knack Builder, add this code to your Custom JavaScript:

// This adds the logged-in user to all forms
$(document).on('knack-view-render.form', function(event, view, data) {
  const name = Knack.getUserAttributes().name
  const email = Knack.getUserAttributes().email
  let text

  if (name && email) {
    text = `You are logged in as ${name} (${email})`
  } else {
    text = `You are logged out.`
  }

  const html = `
    <div id="logged-in-user" class="kn-content">
      ${text}
    </div>
  `
  const htmlAdded = $(`#${view.key} #logged-in-user`).length

  if (!htmlAdded) {
    // Putting it above the Submit Button, but you can put it wherever you want.
    $(`#${view.key} form .kn-submit`).prepend(html)
  }
})

This shows the logged-in user on all forms. If you only want to show it on one form, change the code slightly. For example if your form is view_123, replace knack-view-render.form with knack-view-render.view_123

Hope that helps.

Ian
Knack Pros

1 Like

@KnackPros - Nice one Ian :+1:

1 Like

This is what I was looking for, thank you very much.

1 Like