How to set statusCode on Apex RemoteAction? - salesforce

I am using Apex RemoteAction
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction. SomeTestControllerController.oneRemoteAction}',
'someString',
function(result, event){
// Handle ...
},
{escape: true}
);
On the event there are statusCode inside.
{
'action': "SomeTestControllerController"
'method': "oneRemoteAction"
'ref': false
'result': false
'status': true
'statusCode': 200
'tid': 2
'type': "rpc"
}
How I can set that statusCode from Apex code ?
#RemoteAction
public static MyDtoObject oneRemoteAction(String Oneparam) {
// Set the statusCode ...
return null;
}

Related

Grails 3.3.9 No Session found for current thread

I'm using grails 3.3.9 with a sql server db. I'm using default scaffold-ed code for my domain class. When I hit the index page, I get the No Session found for current thread error. For using the default scaffold-ed code, I'm a bit stumped as to why this is happening. In Grails 2.x once I scaffold the app just works. Anyway here is my code and hopefully someone can shed some light on what I don't obviously know:
application.yml
hibernate:
cache:
queries: false
use_second_level_cache: false
use_query_cache: false
dataSource:
pooled: true
jmxExport: true
driverClassName: org.h2.Driver
username: sa
password: ''
environments:
development:
dataSource:
dbCreate: create-drop
url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
dataSources:
tst:
dbCreate: update
url: jdbc:sqlserver://TESTSERVER;databaseName=Technician;useNTLMv2=true
driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
dialect: org.hibernate.dialect.SQLServer2012Dialect
pooled: true
username: user
password: 'pass'
formatSql: true
logSql: true
test:
dataSource:
dbCreate: update
url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
production:
dataSource:
dbCreate: none
url: jdbc:h2:./prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
properties:
jmxEnabled: true
initialSize: 5
maxActive: 50
minIdle: 5
maxIdle: 25
maxWait: 10000
maxAge: 600000
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1
validationQueryTimeout: 3
validationInterval: 15000
testOnBorrow: true
testWhileIdle: true
testOnReturn: false
jdbcInterceptors: ConnectionState
defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
build.gradle
buildscript {
repositories {
mavenLocal()
maven { url "https://repo.grails.org/grails/core" }
}
dependencies {
classpath "org.grails:grails-gradle-plugin:$grailsVersion"
classpath "org.grails.plugins:hibernate5:${gormVersion-".RELEASE"}"
classpath "com.bertramlabs.plugins:asset-pipeline-gradle:2.15.1"
}
}
version "0.1"
group "tstsupport"
apply plugin:"eclipse"
apply plugin:"idea"
apply plugin:"war"
apply plugin:"org.grails.grails-web"
apply plugin:"asset-pipeline"
apply plugin:"org.grails.grails-gsp"
repositories {
mavenLocal()
maven { url "https://repo.grails.org/grails/core" }
}
dependencies {
compile "org.springframework.boot:spring-boot-starter-logging"
compile "org.springframework.boot:spring-boot-autoconfigure"
compile "org.grails:grails-core"
compile "org.springframework.boot:spring-boot-starter-actuator"
compile "org.springframework.boot:spring-boot-starter-tomcat"
compile "org.grails:grails-web-boot"
compile "org.grails:grails-logging"
compile "org.grails:grails-plugin-rest"
compile "org.grails:grails-plugin-databinding"
compile "org.grails:grails-plugin-i18n"
compile "org.grails:grails-plugin-services"
compile "org.grails:grails-plugin-url-mappings"
compile "org.grails:grails-plugin-interceptors"
compile "org.grails.plugins:cache"
compile "org.grails.plugins:async"
compile "org.grails.plugins:scaffolding"
compile "org.grails.plugins:events"
compile "org.grails.plugins:hibernate5"
compile "org.hibernate:hibernate-core:5.1.16.Final"
compile "org.grails.plugins:gsp"
console "org.grails:grails-console"
profile "org.grails.profiles:web"
runtime "org.glassfish.web:el-impl:2.1.2-b03"
runtime "com.h2database:h2"
runtime "org.apache.tomcat:tomcat-jdbc"
runtime "com.bertramlabs.plugins:asset-pipeline-grails:2.15.1"
runtime "com.microsoft.sqlserver:mssql-jdbc:7.2.1.jre8"
testCompile "org.grails:grails-gorm-testing-support"
testCompile "org.grails.plugins:geb"
testCompile "org.grails:grails-web-testing-support"
testRuntime "org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1"
testRuntime "net.sourceforge.htmlunit:htmlunit:2.18"
}
bootRun {
jvmArgs('-Dspring.output.ansi.enabled=always')
addResources = true
String springProfilesActive = 'spring.profiles.active'
systemProperty springProfilesActive, System.getProperty(springProfilesActive)
}
assets {
minifyJs = true
minifyCss = true
}
Domain class: TST_Customer.groovy
package TSTSupport
class TST_Technician {
String techCode
String techName
boolean tec990Flag
boolean tecCCFlag
Date tecCreateDate
String tecCreatedBy
Date tecModifyDate
String tecModifiedBy
boolean tecActiveFlag
static constraints = {
techCode shared: "techCode"
techName blank: false, maxSize: 75
tecCreatedBy blank: false, maxSize: 35
tecModifyDate nullable: true
tecModifiedBy blank: false, maxSize: 35
}
static mapping = {
datasource "tst"
table name: "lkp_Technician", schema: "dbo", catalog: "Technician"
version false
id generator: 'assigned', name: 'techCode', type: 'string'
techCode column: '[TechnicianCode]'
techName column: '[TechnicianName]'
tec990Flag column: '[Tech990Flag]'
tecCCFlag column: '[TechCCFlag]'
tecCreateDate column: '[TechCreateDate]'
tecCreatedBy column: '[TechCreatedBy]'
tecModifyDate column: '[TechModifyDate]'
tecModifiedBy column: '[TechModifiedBy]'
tecActiveFlag column: '[TechActiveFlag]'
}
}
Controller
package TSTSupport
import grails.validation.ValidationException
import static org.springframework.http.HttpStatus.*
class TST_CustomerController {
TST_CustomerService TST_CustomerService
static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
respond TST_CustomerService.list(params), model:[TST_CustomerCount: TST_CustomerService.count()]
}
def show(Long id) {
respond TST_CustomerService.get(id)
}
def create() {
respond new TST_Customer(params)
}
def save(TST_Customer TST_Customer) {
if (TST_Customer == null) {
notFound()
return
}
try {
TST_CustomerService.save(TST_Customer)
} catch (ValidationException e) {
respond TST_Customer.errors, view:'create'
return
}
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.created.message', args: [message(code: 'TST_Customer.label', default: 'TST_Customer'), TST_Customer.id])
redirect TST_Customer
}
'*' { respond TST_Customer, [status: CREATED] }
}
}
def edit(Long id) {
respond TST_CustomerService.get(id)
}
def update(TST_Customer TST_Customer) {
if (TST_Customer == null) {
notFound()
return
}
try {
TST_CustomerService.save(TST_Customer)
} catch (ValidationException e) {
respond TST_Customer.errors, view:'edit'
return
}
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.updated.message', args: [message(code: 'TST_Customer.label', default: 'TST_Customer'), TST_Customer.id])
redirect TST_Customer
}
'*'{ respond TST_Customer, [status: OK] }
}
}
def delete(Long id) {
if (id == null) {
notFound()
return
}
TST_CustomerService.delete(id)
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.deleted.message', args: [message(code: 'TST_Customer.label', default: 'TST_Customer'), id])
redirect action:"index", method:"GET"
}
'*'{ render status: NO_CONTENT }
}
}
protected void notFound() {
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'TST_Customer.label', default: 'TST_Customer'), params.id])
redirect action: "index", method: "GET"
}
'*'{ render status: NOT_FOUND }
}
}
}
Service
package TSTSupport
import grails.gorm.services.Service
#Service(TST_Customer)
interface TST_CustomerService {
TST_Customer get(Serializable id)
List<TST_Customer> list(Map args)
Long count()
void delete(Serializable id)
TST_Customer save(TST_Customer TST_Customer)
}
I actually had to Google the answer (none of the suggestions given to me worked for me). Anyway, in the controller you prefix right above the classname
#Transactional("name of datasource")
Full example:
package TSTSupport
import grails.validation.ValidationException
import static org.springframework.http.HttpStatus.*
#Transactional("tst")
class TST_CustomerController {
TST_CustomerService TST_CustomerService
static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
respond TST_CustomerService.list(params), model:[TST_CustomerCount: TST_CustomerService.count()]
}
def show(Long id) {
respond TST_CustomerService.get(id)
}
def create() {
respond new TST_Customer(params)
}
def save(TST_Customer TST_Customer) {
if (TST_Customer == null) {
notFound()
return
}
try {
TST_CustomerService.save(TST_Customer)
} catch (ValidationException e) {
respond TST_Customer.errors, view:'create'
return
}
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.created.message', args: [message(code: 'TST_Customer.label', default: 'TST_Customer'), TST_Customer.id])
redirect TST_Customer
}
'*' { respond TST_Customer, [status: CREATED] }
}
}
def edit(Long id) {
respond TST_CustomerService.get(id)
}
def update(TST_Customer TST_Customer) {
if (TST_Customer == null) {
notFound()
return
}
try {
TST_CustomerService.save(TST_Customer)
} catch (ValidationException e) {
respond TST_Customer.errors, view:'edit'
return
}
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.updated.message', args: [message(code: 'TST_Customer.label', default: 'TST_Customer'), TST_Customer.id])
redirect TST_Customer
}
'*'{ respond TST_Customer, [status: OK] }
}
}
def delete(Long id) {
if (id == null) {
notFound()
return
}
TST_CustomerService.delete(id)
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.deleted.message', args: [message(code: 'TST_Customer.label', default: 'TST_Customer'), id])
redirect action:"index", method:"GET"
}
'*'{ render status: NO_CONTENT }
}
}
protected void notFound() {
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'TST_Customer.label', default: 'TST_Customer'), params.id])
redirect action: "index", method: "GET"
}
'*'{ render status: NOT_FOUND }
}
}
}

save nested data in ExtJS 4

I am trying to save nested data which is captured in a Form. (I also read this question)
Here is how the model looks like
Ext.define('App.model.Team',{
extend:'Ext.data.Model',
idProperty:'id',
fields:[
{name:'id', type:'int'},
{name:'name', type:'string'},
{name:'description', type:'string'},
{name:'orgUnitName', type:'string', mapping:'orgUnit.name'}, <----
],
proxy: {
type:'ajax',
url:'/odb/myteams/',
reader: {
type:'json',
root:'data'
}
}
});
In Controller...
saveNewTeam: function( button, e, eOpts ) {
win = button.up( 'window' ),
form = win.down( 'form' ),
isForm = form.getForm();
record = isForm.getRecord(),
values = isForm.getValues(),
record.set( values );
var jsonData = Ext.JSON.encode(isForm.getValues());
Ext.Ajax.request({
url : '/odb/myteams',
method : 'POST',
headers : {
'Content-Type' : 'application/json'
},
params : jsonData,
success: function (form, action) {
Ext.Msg.alert('Status', 'Saved successfully.');
win.close();
},
failure: function (form, action) {
if (action.failureType === Ext.form.action.Action.SERVER_INVALID) {
Ext.Msg.alert('SERVER_INVALID', action.result.message);
}
}
});
},
I get bad request exception.
POST http://odb/myteams?_dc=1407243897827 400 (Bad Request)
looks like the data which is sent is not in correct json format?
This is what the server expects:
{
name: "Operation addedd",
description: "Operation DataBase",
orgUnit:{
name:'DATA DATAPROCESSING GMBH'
}
}
This is how request is sent
{
name: "Operation addedd",
description: "Operation DataBase",
orgUnitName:'DATA DATAPROCESSING GMBH'
}

Uncaught TypeError: Cannot read property 'responseText' of undefined

buttons: [
{
text: "Add User",
id: "new-record-add-button",
handler: function() {
var form = this.up('form').getForm();
form.submit({
url: BasePath+'/main/admin/adduser',
method: 'POST',
waitTitle: 'Authenticating',
waitMsg: 'Please Wait',
success: function(form, action) {
win.close()
Ext.Msg.show({
title:'Success'
,msg:'User added successfully'
,modal:true
,icon:Ext.Msg.INFO
,buttons:Ext.Msg.OK
});
},
failure: function(form, action) {
console.log(action.response.responseText);
obj = Ext.JSON.decode(action.response.responseText);
console.log(obj);
Ext.Msg.alert('Error',obj.errors)
form.reset();
}
})
//this.up("window").close();
}
},
{
text: "Cancel",
handler: function() {
this.up("window").close();
}
}
]
I am getting the following error when I reach the failure function in my form:
Uncaught TypeError: Cannot read property 'responseText' of undefined
This is my php code:
public function adduserAction()
{
$response = new JsonModel();
//$error = array();
$errors="";
if(!ctype_alpha($_POST["first_name"])) {
$errors.="First Name cannot contain characters and numbers";
}
if(!ctype_alpha($_POST["last_name"])) {
$errors.="Last Name cannot contain characters and numbers";
}
if(!filter_var($_POST['email_address'], FILTER_VALIDATE_EMAIL)) {
$errors.="Email should be of the format john.doe#example.com";
}
if(empty($_POST["role"])) {
$errors.="Role cannot be empty";
}
if($errors!="") {
$response->setVariables(array("success"=>false, "errors"=>$errors));
}
else {
$response->setVariables(array("success"=>true, "errors"=>$errors));
}
return $response;
}
responseText is an ExtJs thing - it represents the actual text returned from the server (eg, using echo) before being decoded.
You should get it in asynchronous callbacks within the operation or request objects, unless there was a server exception of a sort or if you set success to false, that's why you don't get it in the failure handler.
To really understand what's going on with it I recommend you have a look at Connection.js.
if you do a form submit through ExtJs, then on success of the form submission it needs response.responseText to be set as {"sucess":"true"}. if you are submitting the form to some page you have to make sure that you will be returning this object from backend. Or else you have to override the existing onSuccess method.
The second way is something like this,
Ext.override(Ext.form.action.Submit,{
onSuccess: function(response) {
var form = this.form,
success = true,
result = response;
response.responseText = '{"success": true}';
form.afterAction(this, success);
}
});
Place this snippet in your application and see the magic. Cheers. :)

How to update an extjs window on its button click

Currently i am facing the following problem.
I am displaying after successful call of this ajax request.
function callDesignWindow(){
var serviceType = $("#serviceType").val();
alert(serviceType);
var ptId = $("#pt_id").val();
alert(ptId);
getAjaxPage({
url : "/ajax/NewEform/design.do?serviceType=" + serviceType +"&ptId =" + ptId,
successCallback: function (data) {
showDesignWindow(data);
}
});
searchVisible = true;
}
function showDesignWindow(htmlData){
alert(" In the show Design Window");
var designWindow = new Ext.Window({
title: "E-Form Design Phase",
width:650,
autoHeight: true,
id:'designWindow',
html: htmlData,
closable: false,
y: 150,
listeners: {
beforeclose: function () {
searchVisible = false;
}
},
buttons: [
{
text: 'Add Control', handler: function() {
saveFormControl();
}
},
{
text:'Customize', handler: function() {
designWindow.hide();
callCustomWindow();
}
}
]
});
designWindow.show(this);
}
function saveFormControl(){
alert(" add control button clicked");
if (!validateEformData()) return false;
formname= $("#formname").val();
alert(formname);
controlType= $("#controlType").val();
alert(controlType);
label= $("#labelname").val();
alert(label);
dataType= $("#dataType").val();
required= $("#required").val();
serviceType= $("#serviceType").val();
ptId = $("#ptId").val();
if(controlType == 3){
var itemList = [];
$("#selectedItemLists option").each(function(){
itemList.push($(this).val());
});
}
data = "eform_name=" + formname + "&control=" + controlType + "&serviceType=" + serviceType +"&ptId=" + ptId +"&labelName=" +label+ "&dataType=" +dataType+"&required="+required+"&items="+itemList;
alert(data);
$.ajax( {
type : "POST",
url : "/ajax/eformDetails/save.do",
data : data,
cache : false,
dataType : "text/html",
timeout: 40000,
error: function (xhr, err)
{
resolveAjaxError(xhr, err);
},
success : function(data) {
// Ext.getCmp('designWindow').close();
// showDesignWindow(data);
}
});
}
Now on success call of the ajax call ("/ajax/eformDetails/save.do") i want to update the designWindow and reset the values.
please help me in this.
If you want to be able to to manipulate our designWindow after you have already created it, you will need to either maintain a reference to it somewhere, or take advantage of the Ext.getCmp method (I would recommend the latter. For example, in your success function:
success: function () {
var myWindow = Ext.getCmp('designWindow');
//do whatever changes you would like to your window
}

Ext.data.HttpProxy callback on failure

I've the following ExtJS. The listener "write" is called when the response is a success (the response is JSON like: {"success":true,"message":"......"}). But how do I attach a callback when the response is not a success? ({"success":false,"message":"......"})
tableStructure.proxy = new Ext.data.HttpProxy({
api: {
read: '/controller/tables/' + screenName + '/getstructure/' + table,
create: '/controller/tables/' + screenName + '/createcolumn/' + table,
update: '/controller/tables/' + screenName + '/updatecolumn/' + table,
destroy: '/controller/tables/' + screenName + '/destroycolumn/' + table
},
listeners: {
write: tableStructure.onWrite
}
});
You want to catch the HttpProxy's exception event.
listeners: {
write: tableStructure.onWrite
exception: function(proxy, type, action, options, response, arg) {
if(type === 'remote') { // success is false
// do your error handling here
console.log( response ); // the response object sent from the server
}
}
}
You can find the full documentation in the Ext docs for Ext.data.HttpProxy down in the events section.
You should be able to make use of the write event itself. The write event's signature is:
write(dataproxy,action,data,response,record,options).
You can access the success variable from the action object and check if the value is true or false. You should be able to access the success variable as:
action.result.success
You can do:
if(action.result.success != true ) {
// If success is not true
} else {
// If success is true
}
You can also set an exception handler on the Ext.data.Store wrapping the HttpProxy, provided that you send a response code other than 200.
var store = new CQ.Ext.data.Store({
proxy : new CQ.Ext.data.HttpProxy({
method : "GET",
url : '/some_url'
}),
reader : new CQ.Ext.data.JsonReader(),
baseParams : {
param : 'some value'
}
});
store.on("beforeload", function() {
CQ.Ext.getBody().mask("Please wait...", false);
});
store.on("exception", function() {
CQ.Ext.getBody().unmask();
CQ.Ext.Msg.show({
title: 'Error',
msg: '<span style="color:red">Bad request.</span><br/>',
icon: CQ.Ext.Msg.ERROR,
buttons: CQ.Ext.Msg.OK
});
});

Resources