Button to submit the PDF and create new record

sunilsargam
Tera Guru

Hello team,

 

Good day!!

 

I have a scenario where in portal widget i need to create a submit button, once button is clicked, i should get the popup to add PDF. Once PDF is submitted, a record should be created in incident table with the attachment.

 

Thank you

Sunil Sargam

1 ACCEPTED SOLUTION

Muhammad Salar
Giga Sage

Try this in widget
HTML:
<button class="btn btn-primary" ng-click="c.uploadAndSubmit($event)">Upload & Submit Incident</button>
<input type="file" accept=".pdf" style="display:none" id="fileToUpload" onchange="angular.element(this).scope().setAndSubmitFile(this)" />

Client Controller:

api.controller = function($scope, $http, $element) {
  var c = this;

  c.uploadAndSubmit = function($event) {
    $event.stopPropagation();
    var $el = $element.find('input[type=file]');
    $el.val(null);
    $el.click();
  };

  $scope.setAndSubmitFile = function(element) {
    if (element.files.length === 0) return;

    var file = element.files[0];

    // Step 1: Create Incident without file info
    $http.post('/api/now/table/incident', {
      short_description: 'Incident from portal widget'
    }).then(function(response) {
      var incidentSysId = response.data.result.sys_id;
      alert('Incident created: ' + response.data.result.number);

      // Step 2: Upload file as attachment
      c.uploadAttachment(file, incidentSysId);
    }, function(error) {
      alert('Error creating incident: ' + (error.data.error.message || 'Unknown error'));
    });
  };

  c.uploadAttachment = function(file, incidentSysId) {
    var fd = new FormData();
    fd.append('file', file);

    $http.post('/api/now/attachment/file?table_name=incident&table_sys_id=' + incidentSysId + '&file_name=' + encodeURIComponent(file.name),
      fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
      }).then(function(response) {
        alert('Attachment uploaded successfully!');
      }, function(error) {
        alert('Attachment upload failed: ' + (error.data.error.message || 'Unknown error'));
      });
  };
}; 



View solution in original post

5 REPLIES 5

Ankur Bawiskar
Tera Patron
Tera Patron

@sunilsargam 

What's your actual business requirement?

It would be great if you share that so that better alternatives can be provided.

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader