Set grid field from uploaded filename

From pmusers
Jump to: navigation, search

This example shows how to use JavaScript to get the filename from an uploaded file in a grid and use that filename to set the value of a text field in the same grid row.

Dynaform: Set grid field from uploaded filename.json (right click and select Save Link As)
Author: Amos Batto <amos[en]>
Version: 1.0 (2018-07-23)
Tested in: PM 3.3.10 Community in Debian 9.5 with Firefox 60.5

Create the following Dynaform containing a grid with a File field:

GridFieldUploadedFilename FormInDesigner.png

The fields in this Dynaform are:

  • A grid with the ID "productsList", which contains the following fields:
    • A text field with the ID "productName"
    • A file field with the ID "productFile"
  • A submit button

Then, add the following JavaScript code to the Dynaform:

//change to the ID of the grid and the File field in the grid:
var reFileInGrid = /^\[productsList\]\[(\d+)\]\[productFile\]$/;

var formId = $("form").prop("id");

$("#"+formId).setOnchange( function(fieldId, filename, oldValue) {
  var aMatch = fieldId.match(reFileInGrid);

  if (aMatch) {
    var rowNo = aMatch[1];
    var basename = filename;
    if (filename.lastIndexOf(".") != -1) {       
      basename = filename.substring(0, filename.lastIndexOf("."));
    //set the file's basename in the "productName" field for the same grid row:
    $("#productsList").setValue(basename, rowNo, 1); 

When the user uploads a file, the basename of the file will be taken an inserted in the "productName" field in the same grid row:

GridFieldUploadedFilename FormInUse.png