ServiceNow - Call a client script from form button click event to save image and caption - servicenow

I was trying to create custom feature in User(sys_user) section to Save a photo and caption to a custom table. I want to save the photo and caption and show all the uploaded photo as thumbnail along with caption. But when I tried to call client-script it is not even trigger the function in client script. Following are the steps i followed
Created a UI macro with following code
<?xml version="1.0" encoding="utf-8" ?>
<j:jelly trim="false" xmlns:j="jelly:core" xmlns:g="glide" xmlns:j2="null" xmlns:g2="null">
<div class="container">
<g:ui_form>
<h1>Choose an image file:</h1>
<p>Supported file types: .jpg, .png, .bmp, .gif, .jpeg, .ico, .svg</p>
<div class="row">
<input name="site_photo_upload" id="site_photo_upload" type="file" class="upld-file" style="padding:20px;"></input>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="fieldone" style="width:100px">Description</label>
<div class="col-sm-10">
<input type="text" name="site_photo_caption" id="site_photo_caption" class="form-control col-md-3" id="fieldone"
placeholder="Enter Description maximum 40 letters..." style="width:300px;height:75px;"></input>
</div>
</div>
<div class="form-group" style="padding:20px;">
<button id="btn_cancel">Cancel</button>
<g:dialog_button id="btn_submit_site_photo" name="btn_submit_site_photo" onclick="saveValues()" type="button" class="btn">Upload</g:dialog_button>
</div>
</g:ui_form>
</div>
<div class="container" style="padding:30px 0;border-top:1px solid #ccc;">
<div class="card-deck">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-3 col-xl-3" style="padding:0;">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
<img class="card-img-top" style="width:100%;" src="https://picsum.photos/309/200?image=1050"
alt="Card image cap"></img>
<p class="card-text" style="padding:10px 0;">caption placeholder</p>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-3 col-xl-3" style="padding:0;">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
<img class="card-img-top" style="width:100%;" src="https://picsum.photos/309/200?image=1050"
alt="Card image cap"></img>
<p class="card-text" style="padding:10px 0;">caption placeholder</p>
</div>
</div>
</div>
</div>
</j:jelly>
Created a formatter and added the formatter in User form through 'Form Design'. It successfully displayed as below
Create a table 'u_sitephoto' with columns site_photo, site_photo_caption and a reference column userid to User table
Create a client script in 'OnLoad' type
function saveValues() {
var site_photo = document.getElementById("site_photo_upload").value;
var site_photo_caption = document.getElementById("site_photo_caption").value;
var sitephoto_record = new GlideRecord('u_sitephoto');
sitephoto_record.initialize();
sitephoto_record.setValue('site_photo', site_photo);
sitephoto_record.setValue('site_photo_caption', site_photo_caption);
sitephoto_record.insert();
}
But I am getting the following error when clicking the Upload button
Uncaught ReferenceError: saveValues is not defined at
HTMLButtonElement.onclick
I would like to get some help for resolving the following issues
To resolve above error, and trigger the client script on button click
Reload the image thumbnails(currently added some placeholder images as shown in the image) with all the uploaded photos for that user
On cancel button click remove the selected photo for uploading
Thanks in advance for your great suggestions & helps

Try following about how to resolve the 1st issue.
UI macro is rendered in server side, so it can't retrieve functions from a Client Script.
You can define the function directly in <script> tag of UI macro.
Within the function, use GlideAjax to call backend Script Include in which you can put your code of creating a new record of 'u_sitephoto' table.
BTW, I am using Paris version of ServiceNow.
Sample function in UI macro:
function saveValues() {
<!-- You could use $j to call JQuery in UI macro -->
var site_photo = $j("#site_photo_upload").get(0).files[0];
var site_photo_caption = $j("#site_photo_caption").val();
var ajax = new GlideAjax('SitePhoneUtils');
ajax.addParam('sysparm_name', 'savePhotos');
ajax.addParam('sysparm_site_photo', site_photo);
ajax.addParam('sysparm_photo_caption', site_photo_caption);
ajax.getXML();
}
Sample function in Script Include - SitePhoneUtils
savePhotos: function() {
var site_photo = this.getParameter('sysparm_site_photo');
var site_photo_caption = this.getParameter('sysparm_site_photo_caption');
var gr = new GlideRecord('u_sitephoto');
gr.initialize();
gr.site_photo = site_photo;
gr.site_photo_caption = site_photo_caption;
gr.insert();
}

Related

Datepicker - Not Showing properly in Modal View

I Am trying to open datepicker from textbox. Datepicker open but not showing properly. ( Check Ref Image ).
Can anyone help me ....
Script:-
<script>
$('#milksaledate').datepicker({
format: 'yyyy-mm-dd',
autoclose: true
});
</script>
Modal Text Box
<div class="col-md-3">
<div class="form-group">
<label>Date of Sale <span class="validate">*</span> :</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-calendar-alt"></i></span>
</div>
<input type="text" class="form-control" name="milksaledate" id="milksaledate">
</div>
</div>
</div>
Script
<script src="plugins/datatables/jquery-3.5.1.js"></script>
<script src="plugins/jquery-ui/jquery-ui.min.js"></script>
[![enter image description here][1]][1]<script src="plugins/jquery-ui/jquery-ui.js"></script>
There could be multiple reasons for this:
Is it maybe possible you have multiple inputs where the id is milksaledate? I think in general it's better to use something like $('.datepicker').datepicker(..) and add class='datepicker' to each input which uses the datepicker.
When are you calling $('#milksaledate').datepicker(..)? Is it on page load, or after the modal has opened? Because if you call this code before a modal has initialized, the datepicker will not affect the modal.
Another reason could be due to z-index or other style issues concerned specifically to jquery-ui

How to use laravel shweshi/OpenGraph

Here how to use it according to its GitHub
I already install the package:
Use Opengraph
$data = OpenGraph::fetch("http://www.addemyplus.com/blogs/my-faith-for-your-love");
that may return an array:
{"type":"website","title":"My Faith For Your Love","description":"","image":"http:\/\/www.addemyplus.com\/images\/frontend_images\/blogs\/medium\/57670.jpg"}
My problem is how can I use it on my blade that whenever I type a link in the form it will fetch the Og data of that site.
and show below the image and description
I have this code on form:
<form action="{{route('store_post_path')}}" method="POST">
{{csrf_field()}}
<div class="form-group">
<label class="sr-only" for="title">title</label>
<input type="text" class="form-control" name="title" placeholder="Your Post Title or Question">
</div>
<div class="form-group">
<label class="sr-only" for="post">post</label>
<textarea class="form-control" name="post_content" id="post_content" rows="3" placeholder="Briefly explain your question or Your Post Content"></textarea>
</div>
<div class="tab-pane fade" id="images" role="tabpanel" aria-labelledby="images-tab">
<div class="form-group">
<div class="custom-file">
</div>
</div>
<div class="py-4"></div>
</div>
<div class="btn-toolbar justify-content-between">
<div class="btn-group">
<button type="Submit" class="btn btn-primary">Share your Post</button>
</div>
</div>
</form>
How can I use the code to fetch the Og property of the link? I want to view the image and title of the link below before submitting my post.. Please show some tutorial sites for this.
Get the link from the form in post content. You can do it using regex.
function getUrl($string)
{
$regex = '/https?\:\/\/[^\" ]+/i';
preg_match_all($regex, $string, $match);
return ($match);
}
$url = getUrl($string)
If there are any links in post content you will get array of links.
Use OpenGraph::fetch($url) to fetch the OG data of the url. That you can show in the view.

i recently used JCrop in my laravel project , but although i choose a photo and its loaded , i get validation error image is requred

I followed this https://www.youtube.com/watch?v=aflTCbGdzDc tutorial, and I managed to include Jcrop in my laravel project, everything is working fine. I click on choose image, I crop the image, and the image is shown in the jcrop image box. but when I submit the form. I get the error in my validation that says, image is required ( i wrote a validation for my image file). why am I getting this error ??? the image is showing in that box. what am I doing wrong ? or is there a problem with JCrop ?!! please help me.
This is the image when I upload :
https://drive.google.com/open?id=1qgEmA9RlKy_eilZohCLajGmnVfqWSB9E
This is the image when I submit and I get the error : https://drive.google.com/open?id=1gSCurwZ50TF_nMZZcWnJ4keBsJmcQKEh
Template Code:
<form method="post" action="{{route('userRegister')}}" enctype="multipart/form-data">
#csrf
<div class="col-md-6 alert alert-danger {{!empty($errors->all()) ? 'show' : 'hide'}}">
<ul style="text-align: right;" dir="rtl">
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
<div class="row col-md-12" dir="rtl">
<div class="input-group col-md-4">
<div class="container" dir="ltr">
<div id="userpic" class="userpic">
<div class="js-preview userpic__preview"></div>
<div class="btn btn-success js-fileapi-wrapper">
<div class="js-browse">
<span class="btn-txt">انتخاب عکس</span>
<input type="file" name="filedata" id="filedata" >
</div>
<div class="js-upload" style="display: none;">
<div class="progress progress-success"><div class="js-progress bar"></div></div>
<span class="btn-txt">در حال بارگذاری</span>
</div>
</div>
</div>
</div>
<div id="popup" class="popup" style="display: none">
<div class="popup__body"><div class="js-img"></div></div>
<div style="margin: 0 0 5px;text-align: center">
<div class="js-upload btn btn_browse btn_browse_small">بارگذاری</div>
</div>
</div>
</div>
</div>
Validation Code:
public function rules()
{
return [
'filedata' => 'required|max:1024',
];
}
public function messages()
{
return [
'filedata.max' => 'سایز تصویر نمیتواند بیش از 2 مگابایت باشد',
'filedata.required' => 'وارد کردن تصویر الزامی است',
];
}
I get this error in my console :
POST http://localhost:8000/server/ctrl.php?fileapi155834626282411 404 (Not Found) FileAPI.min.js:2
After talking to you in the comments, it would appear your getting 404 errors on the FileAPI javascript files.
You were using the following configuration for your FileAPI:
var FileAPI = { debug:true, media:true, staticPath:'{{asset('crop-userpic\FileAPI')}}' };
This was setting your staticPath to the /resources/assets/crop-userpic/FileAPI directory, which placed them outside of the webroot of your website.
You need to set the staticPath to the location of the FileAPI javascript files within your public directory so they can be accessed by jcrop.
Example Usage
<!-- include jquery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<!-- Set FileAPI settings -->
<script>
window.FileAPI = {
debug: false,
media: true,
staticPath: '/js/jquery.fileapi/FileAPI/'
};
</script>
<script src="/js/jquery.fileapi/FileAPI/FileAPI.min.js"></script>
<script src="/js/jquery.fileapi/FileAPI/FileAPI.exif.js"></script>
<script src="/js/jquery.fileapi/jquery.fileapi.min.js"></script>
<script src="/js/jcrop/jquery.Jcrop.min.js"></script>
In the above example staticPath is the path to the files FileAPI.min.js and FileAPI.exif.js.
You should make sure you have those files accessible from within the /public/js/jquery.fileapi/FileAPI/.

New to Laravel, trying to integrate Square Payment Form

I've been following the instructions on Square's website.
I've got all the code I need plugged into my application as shown on square, but the asset('js/square.js') call didn't find the file for some reason. So, I just added the script to the end of the resources/js/app.js file, doesn't seem to have any errors but the form doesn't look right..
<form id="nonce-form" novalidate action="PATH/TO/PAYMENT/PROCESSING/PAGE" method="post">
#csrf
<fieldset>
<span class="label">Card Number</span>
<div id="sq-card-number"></div>
<div class="third">
<span class="label">Expiration</span>
<div id="sq-expiration-date"></div>
</div>
<div class="third">
<span class="label">CVV</span>
<div id="sq-cvv"></div>
</div>
<div class="third">
<span class="label">Postal</span>
<div id="sq-postal-code"></div>
</div>
</fieldset>
<button id="sq-creditcard" class="button-credit-card" onclick="requestCardNonce(event)">Pay $1.00</button>
<div id="error"></div>
<!--
After a nonce is generated it will be assigned to this hidden input field.
-->
<input type="hidden" id="card-nonce" name="nonce">
</form>

Reload the page to get page source for error, dont know what is wrong

Hi i am new to zend framework , i have created an app which will allow the user to edit an image and put some text inside the image, so i have decided to learn zend framework, by implementing personalmug application,
I have uploaded the app to the hosted server subdomain, but for some reason my application is not working same like on localhost. on localhost it is working fine but on the hosted server i dont know what is worng, but there some questions about redirecting on localhost after ajax success.
The issues are given below.
Question no 1.
when i Open the home page and click the customize button it will display a model which contains a form, with four input fields, and when i type in the 4 lines and click the preview button, it will call controller personalmug and the action is preview, the preview action will create an image from existing image which is in public/img/ folder, now it is not creating the image to the folder public/img/image_uri and the responce is blank page, and in the firebug the html the message is "Reload the page to get the source". and when i reload the page the image is not there and the image is not in the public/img/image_uri folder on the hosted server, and the session is not created i think the preview action has some issues. but dont know where i am worng, i have tried to google it from 4 days but no success.
The same thing is working on localhost.
Question number 2
i want to redirect the page after clicking the save button on preview.phtml page, now i have a save action in controller, which will save the data on localhost mysql database, and it is redirecting but only in the firbug , the actuall page is not redirecting, i have tried to use alerts in ajax success , but no use it is not displaying the message.
Please help and Thanks in advance. i would appreciate my code corrections. and some code samples. thanks again.
Index.phtml
<div class="row top-buffer">
<div class="span9">
<div class="row">
<div class="col-md-4"><img src='<?php echo $this->basePath('img/whitemug toxic fox.jpg') ?>'class="img-responsive"/></div>
<div class="col-md-6">
<h3><strong>Personal Mug</strong></h3>
<h3><small>Show your amazing coach just how great he is with this No.1 Coach Mug. This mug is a great gift for any occasion, make your gift extra special by personalising it with any name of your choice. This thoughtful gift is guaranteed to impress!</small></h3>
<a name="fulldescription">Read Full Description</a>
<div class="row top-buffer">
<div class="col-md-8">
<button class="btn btn-success btn-lg btn-block" data-toggle="modal" data-target="#myModal">Customize</button>
</div>
</div>
<div class="row top-buffer">
<ul>
<li>
The mug has space for a maximum of 48 characters, over a maximum of 4 lines.
</li>
<li>
Free Delivery when you spend over £40
</li>
<li>
Guaranteed Fast, Secure Shipping
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 ">
<h3><strong>Personal Mug</strong></h3>
<h4><small>Is your coach simply the best?</small></h4>
<h4>Reward them with this amazing No.1 Coach Mug. This mug features a fabulous award design with the message COACH (any name) no.1! Make this thoughtful gift extra special and personal by adding your coaches name!</h4>
</div>
<div class="col-md-6 ">
<?php foreach($personalmugs as $personalmug) : ?>
<div class="col-md-3 top-buffer"> <a href="#">
<img src="<?php echo $this->basePath($this->escapeHtml($personalmug->image_uri)); ?>" class="img-thumbnail img-responsive">
</a>
</div>
<?php endforeach; ?>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Submit text</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" action="personal-mug/preview" role="form" method="POST">
<div class="form-group">
<label for="inputText" class="col-sm-2 control-label">Text</label>
<div class="col-sm-10">
<input class="form-control" type="text" name="mugtext1" maxlength="12" placeholder=Line1 pattern="^[a-zA-Z0-9\s]+" title="Only Alphabets and Numbers" min="1" max="12" required>
<input class="form-control" type="text" name="mugtext2" maxlength="12" placeholder=Line2 pattern="^[a-zA-Z0-9\s]+" title="Only Alphabets and Numbers" min="1" max="12" required>
<input class="form-control" type="text" name="mugtext3" maxlength="12" placeholder=Line3 pattern="^[a-zA-Z0-9\s]+" title="Only Alphabets and Numbers" min="1" max="12" required>
<input class="form-control" type="text" name="mugtext4" maxlength="12" placeholder=Line4 pattern="^[a-zA-Z0-9\s]+" title="Only Alphabets and Numbers" min="1" max="12" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button name="submit" value="submit" type="submit" class="btn btn-default">Preview</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
The preview phtml file code.
<div class="row top-buffer">
<div class="span9">
<div class="row">
<div class="col-md-4"><img id="mug1" name="mug1" src='
<?php
if(isset($_SESSION['preview_image_id']) && !empty($_SESSION['preview_image_id'])){
$ID = $_SESSION['preview_image_id'];
echo $this->basePath("img/image_uri/$ID.jpg");
} ?>'class="img-responsive"/></div>
<div class="col-md-6">
<h3><strong>Personal Mug</strong></h3>
<h3><small>Show your amazing coach just how great he is with this No.1 Coach Mug. This mug is a great gift for any occasion, make your gift extra special by personalising it with any name of your choice. This thoughtful gift is guaranteed to impress!</small></h3>
<div class="row top-buffer">
<div class="col-md-8">
<a id ="buttonSave" class="btn btn-success btn-lg btn-block">Save</a>
<a class="btn btn-success btn-lg btn-block" href="<?php echo $this->url('personal-mug', array('action'=>'add'));?>">Edit</a>
</div>
</div>
<div class="row top-buffer">
<ul>
<li>
The mug has space for a maximum of 48 characters, over a maximum of 4 lines.
</li>
<li>
Free Delivery when you spend over £40
</li>
<li>
Guaranteed Fast, Secure Shipping
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<script>
$('#buttonSave').click(function (){
var image_uri = $("#mug1").attr("src");
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://toxicfox.com/personal-mug/add',
async: false,
// you can use an object here
data: { image_uri: image_uri},
success: function(json) {
console.log(json.image_uri);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
});
</script>
The controller.
namespace PersonalMug\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use PersonalMug\Model\PersonalMug;
use PersonalMug\Form\PersonalMugForm;
class PersonalMugController extends AbstractActionController{
protected $personalmugTable;
public function getPersonalMugTable(){
if(!$this->personalmugTable){
$sm = $this->getServiceLocator();
$this->personalmugTable = $sm->get('PersonalMug\Model\PersonalMugTable');
}
return $this->personalmugTable;
}
public function indexAction(){
return new ViewModel(
array(
'personalmugs' => $this->getPersonalMugTable()->fetchAll(),
));
}
public function addAction(){
$data['image_uri'] = $this->getRequest()->getPost('image_uri');
$personalmug = new PersonalMug();
$personalmug->exchangeArray($data);
$this->getPersonalMugTable()->save($personalmug);
return $this->redirect()->toRoute('personal-mug');
}
public function previewAction(){
if(isset($_POST['submit'])){
session_start();
$ID = uniqid();
$_SESSION['preview_image_id'] = $ID;
$text1 = htmlspecialchars($_POST['mugtext1']);
$text2 = htmlspecialchars($_POST['mugtext2']);
$text3 = htmlspecialchars($_POST['mugtext3']);
$text4 = htmlspecialchars($_POST['mugtext4']);
$this->getPersonalMugTable()->preview($ID,$text1,$text2,$text3,$text4);
}
}
The personalmug table file.
namespace PersonalMug\Model;
use Zend\Db\TableGateway\TableGateway;
use Zned\ServerUrl\Helper;
class PersonalMugTable{
protected $tableGateway;
public function __construct(TableGateway $tableGateway){
$this->tableGateway = $tableGateway;
}
public function fetchAll(){
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getImage($image_id){
$image_id = (int) $image_id;
$rowset = $this->tableGateway->select(array('image_id' => $image_id));
$row = $rowset->current();
if(!$row){
throw new \Exception("Could not find row $image_id");
}
return $row;
}
public function save(PersonalMug $personalmug){
$data = array(
'image_id' => $personalmug->image_id,
'image_uri' => $personalmug->image_uri,
);
$image_id = (int) $personalmug->image_id;
if($image_id == 0){
$this->tableGateway->insert($data);
}else{
if($this->getImage($image_id)){
$this->tableGateway->update($data, array('image_id' => $image_id));
}else{
throw new \Exception('Mug id does not exist');
}
}
}
public function deleteAlbum($image_id){
$this->tableGateway->delete(array('image_id' => (int) $image_id));
}
public function preview($ID,$text1,$text2,$text3,$text4){
strtoupper($text1);
strtoupper($text2);
strtoupper($text3);
strtoupper($text4);
// load the image from the file specified:
$im = imagecreatefromjpeg('public/img/whitemug%20toxic%20fox.jpg');
// if there's an error, stop processing the page:
if(!$im){
die("");
}
// define some colours to use with the image
$black = imagecolorallocate($im, 0, 0, 0);
// now we want to write in the centre of the rectangle:
$font ="public/fonts/arial.ttf"; // store the int ID of the system font we're using in $font
// store the text we're going to write in $text
// finally, write the string:
imagettftext($im,60,0,260,460,$black,$font,$text1);
imagettftext($im,60,0,260,560,$black,$font,$text2);
imagettftext($im,60,0,260,660,$black,$font,$text3);
imagettftext($im,60,0,260,760,$black,$font,$text4);
imagejpeg($im, "public/img/image_uri/$ID.jpg");
// tidy up
imagedestroy($im);
}
}
I think you are getting an error in much lower level than the framework. Try to see Apache "error.log" for more details about the error. Please let me know if you find anything.

Resources