Content in an embedded form textarea not being set to a process variable - camunda

Within a user task, the embedded form markup is
...
<div class="form-group">
<textarea class="form-control"
cam-variable-name="jobDescription"
cam-variable-type="String"
name="jobDescription">
</textarea>
</div>
...
There is a process variable jobDescription that has been set - this has been verified via the Tomcat logs.
The problem is that content of the textarea is not being set to that of the process variable.
Camunda 7.10 is being used and I have checked the Camunda manual 7.10
If the textarea is changed to input type="text", this shows the correct content.

This works for Camunda 7.10.
To populate a textarea, the form needs to use the Camunda form events
<script cam-script type="text/form-script">
var variableManager = camForm.variableManager;
var jobRequestInfo = $scope.jobRequestInfo = {};
var jobDescription = $scope.jobDescription = {};
camForm.on( 'form-loaded', function() {
camForm.variableManager.fetchVariable( 'jobRequestInfo' );
camForm.variableManager.fetchVariable( 'jobDescription' );
});
camForm.on( 'variables-fetched', function() {
$scope.jobRequestInfo = camForm.variableManager.variable( 'jobRequestInfo' ).value;
$scope.jobDescription = camForm.variableManager.variable( 'jobDescription' ).value;
});
camForm.on( 'variables-applied', function() {
$( '[name="jobDescription"]' ).val( $scope.jobDescription );
});
camForm.on( 'submit', function( ev ) {
;
});
</script>
...
<div class="form-group">
<label for="jobDescription">Job Description</label>
<textarea class="form-control"
ng-model="jobRequestInfo.description"
name="jobDescription"
rows="20">
</textarea>
</div>
...
There are two process-scoped variables:
jobDescription a String that is populated with the initial value.
jobRequestInfo a POJO with a field description that is populated with the final, edited value.
Note that Camunda does not fully support all HTML types such as radio buttons so beyond basic forms, using the Camunda form events is usually necessary.
Also, using Angular integration and POJO variables, as above, allows a significant reduction in process variables.

Related

How to autofocus an input field in semantic-ui-react?

I'm having a difficult time autofocusing an input field with semantic-ui-react. The documentation doesn't seem to include an autoFocus prop and the focus prop doesn't place the cursor inside the input field as would be expected.
<Form onSubmit={this.handleFormSubmit}>
<Form.Field>
<Form.Input
onChange={e => this.setState({ username: e.target.value })}
placeholder='Enter your username'
fluid />
</Form.Field>
</Form>
EDIT: This code works:
<Form onSubmit={this.handleFormSubmit}>
<Form.Input
onChange={e => this.setState({ username: e.target.value })}
placeholder="Enter your username"
autoFocus
fluid />
</Form>
The focus prop is purely to add a focus effect on the input's appareance, it does not actually set the focus.
Any props unused by Semantic are passed down to the DOM element, so if you set an autoFocus prop, it should go down to the input.
However, as explained in the Form documentation:
Form.Input
Sugar for <Form.Field control={Input} />.
So your code should rather be:
const yourForm = (
<Form onSubmit={this.handleFormSubmit}>
<Form.Input
onChange={e => this.setState({ username: e.target.value })}
onSelect={() => this.setState({ usernameErr: false })}
placeholder="Enter your username"
error={usernameErr}
iconPosition="left"
name="username"
size="large"
icon="user"
fluid
autoFocus
/>
</Form>
)
Note that this only works if you want the focus to happen right when the wrapper component is mounted. If you want to focus the input after it has been mounted, you have to use a ref and call the focus() method on it, just as showed in the documentation, like so:
class InputExampleRefFocus extends Component {
handleRef = (c) => {
this.inputRef = c
}
focus = () => {
this.inputRef.focus()
}
render() {
return (
<div>
<Button content='focus' onClick={this.focus} />
<Input ref={this.handleRef} placeholder='Search...' />
</div>
)
}
}
Hope that helps!
I would have assumed that semantic UI would pass all unknown props to the root element, the input. So if it does, you should be able to add the autoFocus attribute to it, if not, you will have to control which input is being focused in your state.
<Input placeholder='Search...' focus={this.state.focusedElement === "search"}/>
In order to tell the input field to focus, you need to create a reference (ref) to the input field as follows:
import React, { useState, useRef } from 'react';
import { Input, Button } from 'semantic-ui-react';
const SearchInputExample = () => {
const [searchValue, setSearchValue] = useState('');
// Create reference to the input field
const searchRef = useRef(null);
const handleSearchValueChange = event => setSearchValue(event.target.value);
return (
<div>
<Input
placeholder="Search..."
// Assign the ref created to a ref attribute
ref={searchRef}
value={searchValue}
onChange={handleSearchValueChange}
/>
<Button
onClick={() => {
setSearchValue('');
// Use the ref assigned to put the focus inside the input
searchRef.current.focus();
}}
>
Clear search (and focus)
</Button>
</div>
);
};
export default SearchInputExample;
You can read more about the useRef() hook here

How to clear the typeahead input after a result is selected?

I'm using the ng-bootstrap typeahead component to search a customer database. When the user selects a customer from the typeahead results list, I navigate to a customer details page. I've got this working, but I want to clear the input field after navigation has taken place. I've tried setting the model to null or an empty string in the selectItem event logic, but this isn't working:
customer-search-typeahead.component.html
<template #resultTemplate let-r="result" let-t="term">
<div>
<div>
{{r.resource.name[0].given}} {{r.resource.name[0].family}}
</div>
<div>
{{r.resource.birthDate | date: 'dd/MM/yyyy'}}
</div>
</div>
</template>
<input type="text" class="form-control" [resultTemplate]="resultTemplate" (selectItem)="onSelect($event)"
[(ngModel)]="model" placeholder="Start typing a customer name..." [ngbTypeahead]="search"/>
customer-search-typeahead.component.ts
#Component({
selector: 'customer-search-typeahead',
template: require('./customer-search-typeahead.component.html'),
styles: [`.form-control { width: 300px; }`]
})
export class CustomerSearchTypeaheadComponent {
model: any;
searching: boolean;
constructor(private customerService: CustomerService, private router: Router) {}
onSelect($event) {
this.router.navigate(['/customers', $event.item.resource.id]);
this.model = null;
};
search = (text$: Observable<string>) =>
//omitted for brevity
}
The typeahead input looks like this after a selection has been made:
Solution
customer-search-typeahead.component.html
<input type="text" class="form-control" #input [ngbTypeahead]="search" (selectItem)="onSelect($event); input.value='' ">
customer-search-typeahead.component.ts
onSelect($event, input) {
$event.preventDefault();
this.router.navigate(['/customers', $event.item.resource.id]);
};
The issue you witnessing arises from the fact that the NgModel directive is updating model binding asynchronously and the actual model is updated after the onSelect method gets executed. So your model update gets overridden by the NgModel functionality.
Fortunately we (ng-bootstrap authors) got all the flex points in place to cover your use-case :-) There are a couple of things that you could do.
Firstly the $event object passed to the onSelect method has the preventDefault() method and you can call it to veto item selection (and as a result writing back to the model and input field update).
$event.preventDefault() will make sure that the model is not updated and the input field is not updated with the selected item. But text entered by a user will still be part of the input so if you want to clear up this as well you can directly update the input's value property.
Here is code demonstrating all those techniques together:
onSelect($event, input) {
$event.preventDefault();
this.selected.push($event.item);
input.value = '';
}
where input argument is a reference to the input DOM element:
<input type="text" class="form-control" #input
[ngbTypeahead]="search" (selectItem)="onSelect($event, input)">
Finally here is a plunker showing all this in practice: http://plnkr.co/edit/kD5AmZyYEhJO0QQISgbM?p=preview
The above one is template ref value solution.
This is for ngModel solution.
Html code:
<input type="text" class="form-control" [resultTemplate]="resultTemplate" (selectItem)="onSelect($event)"
[(ngModel)]="model" placeholder="Start typing a customer name..." [ngbTypeahead]="search"/>
Component code:
onSelect($event) {
$event.preventDefault();
this.model = null;
this.router.navigate(['/customers', $event.item.resource.id]);
};
$event.preventDefault();
for ngModel value change empty

Google places API only autocompletes street name field . . . but throws no errors

I'm new to Google's Places API. I'm trying to get a Django form to autocomplete, but for some reason, only one of the fields (Street 2) will autocomplete. The rest are just blank. And my console throws no errors, so I really have no idea what the issue is.
The other WEIRD thing . . . the inputs are holding the initial values that I passed to the form from the Django view even though the google autocomplete javascript has set them to "" before trying to autofill them. Is that normal?
Here's the HTML:
<div id="locationField">
<input id="autocomplete" name="search_address" onFocus="geolocate()" placeholder="Search for your address . . ." type="text" />
</div>
<hr class="hr-style">
<div >
<strong>Street</strong>
<input id="street_name" name="street" type="text" value="1030 E State Street" />
</div>
<div >
<strong>Street 2</strong>
<input id="route" name="street2" type="text" value="Apt. 2A" />
</div>
<div >
<strong>City</strong>
<input id="city" name="city" type="text" value="Los Angeles" />
</div>
<div class="6u 12u$(small) ">
<strong>State</strong>
<select id="state" name="state">
<!-- options removed for brevity's sake -->
</div>
<div class="6u 12u$(small) ">
<strong>Zip</strong>
<input id="zipcode" name="zipcode" type="text" value="90210" />
</div>
And the javascript, just copied from Google and modified with my input id's:
//geosearch powered by Google
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
$(function(){
initAutocomplete();
});
var placeSearch, autocomplete;
var componentForm = {
street_name: 'short_name',
route: 'long_name',
city: 'long_name',
state: 'short_name',
zipcode: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{types: ['geocode']});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
// [START region_fillform]
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = "";
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// [END region_fillform]
// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation
I'm thinking it has got to be failing somehow at this if statement in fillinAddress(), but I can't tell why:
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
Any help would be appreciated! And here's a screenshot of the form!
Turns out you can NOT rename the address form components. (I had renamed 'locality' to be 'city' and 'administrative_area_level_1' to be 'state.') I'm so new to this; I had no idea! I just thought that the variable names in the javascript had to match your input id's in your HTML. Turns out the address form components have to stay:
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'

How to add text input to dropzone upload

I'd like to allow users to submit a title for each file that is dragged into Dropzone that will be inputted into a text input. But i don't know how to add it. Everyone can help me?
This is my html code code
<form id="my-awesome-dropzone" class="dropzone">
<div class="dropzone-previews"></div> <!-- this is were the previews should be shown. -->
<!-- Now setup your input fields -->
<input type="email" name="username" id="username" />
<input type="password" name="password" id="password" />
<button type="submit">Submit data and files!</button>
</form>
And this is my script code
<script>
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
url: "upload.php",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
maxFilesize:10,//MB
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
},
accept: function (file, done) {
//maybe do something here for showing a dialog or adding the fields to the preview?
},
addRemoveLinks: true
}
</script>
You can actually provide a template for Dropzone to render the image preview as well as any extra fields. In your case, I would suggest taking the default template or making your own, and simply adding the input field there:
<div class="dz-preview dz-file-preview">
<div class="dz-image"><img data-dz-thumbnail /></div>
<div class="dz-details">
<div class="dz-size"><span data-dz-size></span></div>
<div class="dz-filename"><span data-dz-name></span></div>
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<input type="text" placeholder="Title">
</div>
The full default preview template can be found in the source code of dropzone.js.
Then you can simply pass your custom template to Dropzone as a string for the previewTemplate key of the option parameters. For example:
var myDropzone = new Dropzone('#yourId', {
previewTemplate: "..."
});
As long as your element is a form, Dropzone will automatically include all inputs in the xhr request parameters.
I am doing something fairly similar. I accomplished it by just adding a modal dialog with jquery that opens when a file is added. Hope it helps.
this.on("addedfile", function() {
$("#dialog-form").dialog("open");
});
In my answer, substitute your "title" field for my "description" field.
Add input text or textarea to the preview template. For example:
<div class="table table-striped files" id="previews">
<div id="template" class="file-row">
<!-- This is used as the file preview template -->
<div>
<span class="preview"><img data-dz-thumbnail /></span>
</div>
<div>
<p class="name" data-dz-name></p>
<input class="text" type="text" name="description" id="description" placeholder="Searchable Description">
</div> ... etc.
</div>
</div>
Then in the sending function, append the associated data:
myDropzone.on("sending", function(file, xhr, formData) {
// Get and pass description field data
var str = file.previewElement.querySelector("#description").value;
formData.append("description", str);
...
});
Finally, in the processing script that does the actual upload, receive the data from the POST:
$description = (isset($_POST['description']) && ($_POST['description'] <> 'undefined')) ? $_POST['description'] : '';
You may now store your description (or title or what have you) in a Database etc.
Hope this works for you. It was a son-of-a-gun to figure out.
This one is kind of hidden in the docs but the place to add additional data is in the "sending" event. The sending event is called just before each file is sent and gets the xhr object and the formData objects as second and third parameters, so you can modify them.
So basically you'll want to add those two additional params and then append the additional data inside "sending" function or in your case "sendingmultiple". You can use jQuery or just plain js to get the values. So it should look something like:
this.on("sendingmultiple", function(file, xhr, formData) {
//Add additional data to the upload
formData.append('username', $('#username').val());
formData.append('password', $('#password').val());
});
Here is my solution:
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#myDropzone", {
url: 'yourUploader.php',
init: function () {
this.on(
"addedfile", function(file) {
caption = file.caption == undefined ? "" : file.caption;
file._captionLabel = Dropzone.createElement("<p>File Info:</p>")
file._captionBox = Dropzone.createElement("<input id='"+file.filename+"' type='text' name='caption' value="+caption+" >");
file.previewElement.appendChild(file._captionLabel);
file.previewElement.appendChild(file._captionBox);
}),
this.on(
"sending", function(file, xhr, formData){
formData.append('yourPostName',file._captionBox.value);
})
}
});
yourUploader.php :
<?php
// Your Dropzone file named
$myfileinfo = $_POST['yourPostName'];
// And your files in $_FILES
?>
$("#my-awesome-dropzone").dropzone({
url: "Enter your url",
uploadMultiple: true,
autoProcessQueue: false,
init: function () {
let totalFiles = 0,
completeFiles = 0;
this.on("addedfile", function (file) {
totalFiles += 1;
localStorage.setItem('totalItem',totalFiles);
caption = file.caption == undefined ? "" : file.caption;
file._captionLabel = Dropzone.createElement("<p>File Info:</p>")
file._captionBox = Dropzone.createElement("<textarea rows='4' cols='15' id='"+file.filename+"' name='caption' value="+caption+" ></textarea>");
file.previewElement.appendChild(file._captionLabel);
file.previewElement.appendChild(file._captionBox);
// this.autoProcessQueue = true;
});
document.getElementById("submit-all").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
const myDropzone = Dropzone.forElement(".dropzone");
myDropzone.processQueue();
});
this.on("sending", function(file, xhr, formData){
console.log('total files is '+localStorage.getItem('totalItem'));
formData.append('description[]',file._captionBox.value);
})
}
});
For those who want to keep the automatic and send datas (like an ID or something that does not depend on the user) you can just add a setTimeout to "addedfile":
myDropzone.on("addedfile", function(file) {
setTimeout(function(){
myDropzone.processQueue();
}, 10);
});
Well I found a solution for me and so I am going to write it down in the hope it might help other people also. The basic approach is to have an new input in the preview container and setting it via the css class if the file data is incoming by succeeding upload process or at init from existing files.
You have to integrate the following code in your one.. I just skipped some lines which might necessary for let it work.
photowolke = {
render_file:function(file)
{
caption = file.title == undefined ? "" : file.title;
file.previewElement.getElementsByClassName("title")[0].value = caption;
//change the name of the element even for sending with post later
file.previewElement.getElementsByClassName("title")[0].id = file.id + '_title';
file.previewElement.getElementsByClassName("title")[0].name = file.id + '_title';
},
init: function() {
$(document).ready(function() {
var previewNode = document.querySelector("#template");
previewNode.id = "";
var previewTemplate = previewNode.parentNode.innerHTML;
previewNode.parentNode.removeChild(previewNode);
photowolke.myDropzone = new Dropzone("div#files_upload", {
init: function() {
thisDropzone = this;
this.on("success", function(file, responseText) {
//just copy the title from the response of the server
file.title=responseText.photo_title;
//and call with the "new" file the renderer function
photowolke.render_file(file);
});
this.on("addedfile", function(file) {
photowolke.render_file(file);
});
},
previewTemplate: previewTemplate,
});
//this is for loading from a local json to show existing files
$.each(photowolke.arr_photos, function(key, value) {
var mockFile = {
name: value.name,
size: value.size,
title: value.title,
id: value.id,
owner_id: value.owner_id
};
photowolke.myDropzone.emit("addedfile", mockFile);
// And optionally show the thumbnail of the file:
photowolke.myDropzone.emit("thumbnail", mockFile, value.path);
// Make sure that there is no progress bar, etc...
photowolke.myDropzone.emit("complete", mockFile);
});
});
},
};
And there is my template for the preview:
<div class="dropzone-previews" id="files_upload" name="files_upload">
<div id="template" class="file-row">
<!-- This is used as the file preview template -->
<div>
<span class="preview"><img data-dz-thumbnail width="150" /></span>
</div>
<div>
<input type="text" data-dz-title class="title" placeholder="title"/>
<p class="name" data-dz-name></p><p class="size" data-dz-size></p>
<strong class="error text-danger" data-dz-errormessage></strong>
</div>
<div>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
</div>
</div>
</div>

How to save form data in a cookie (dojo)

I have a contact form where users will enter their details like name, address, phone and so on. Now I have a checkbox (remember me) on the form.. whenever the user checks this, the information should be saved in a cookie and retrieved when the same user visits later. This is how i started..
<tr><td><input id="mycheck" name="mycheck" data-dojo-type="dijit.form.CheckBox" value="" checked="false" onChange="setCookie" > <label for="mycheck" >Remember me </strong></label></td></tr>
setCookie: function () {
cookie("UserInfo", "cookieValue", { expire: 5 });
},
How do i get the cookie values (this should be whole forms data..do i need to use something like byId)...confused..any ideas??
Thanks
see http://dojotoolkit.org/reference-guide/1.7/dojo/cookie.html
if using > 1.7 you should pull in the required module and use it by reference (as it looks like youre doing):
NOTE is not {expire:X} but {expires :x}
<script>
require(["dojo/cookie"], function(cookie){
/* set */
cookie(cookieName, cookieValue, cookieProps);
/* get */
cookie(cookieName);
});
</script>
You can use dojo/dom-form module to pull values and save them for a neet one-liner
<form id="myform">
<input type="text" name="field1" value="value1">
<input type="text" name="field2" value="value2">
<input type="button" name="someButton" value="someValue">
</form>
<script>
require(["dojo/dom-form", "dojo/cookie"], function(domForm, dCookie){
dCookie(
"formdata",
domForm.toJson("myId"),
{expires: 5}
);
// The cookie will read: '{"field1":"value1", "field2":"value2"}'
// Note the button was skipped.
// Buttons only gets sent when used as submitbutton + onclick
});
</script>
Serialize the value to JSON then undo it when you retrieve like so:
//Setting the cookie to hold an array of values.
value = {my:"1",cookie:"2"};
dojo.cookie("myCookie", dojo.toJson(value), {expires: 30});
//Retrieving the cookie.
newValues = dojo.fromJson(dojo.cookie("myCookie"));