• Dale Worthington
  • NEWBIE
  • 40 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 11
    Questions
  • 13
    Replies
Hi All
I have used the help on this board to create to apex triggers which impact the ContentDocumentLink and ContentDocument object. These triggers work great in the sandbox. When i go to deploy these triggers into production i get an error saying that i dont have the right code coverage.

I believe the way to fix this is to write a test class, i have tried to do this with little success. Is there a way i can get around the need for code coverage? Is there an easy way that someone with very rudimentary understanding of apex and write a trigger?

The triggers are:
trigger ContentDocumentLinkTrigger2 on ContentDocumentLink (before delete) {
    for (ContentDocumentLink cdl : Trigger.old) {
         if([SELECT PermissionsModifyAllData FROM Profile WHERE Id = :UserInfo.getProfileId()].PermissionsModifyAllData) {
        return;
    }
        cdl.addError('Document links cannot be removed');
    }
}
and
trigger ContentDocumentTrigger2 on ContentDocument (before delete) {
for(ContentDocument cd : Trigger.old){

    if([SELECT PermissionsModifyAllData FROM Profile WHERE Id = :UserInfo.getProfileId()].PermissionsModifyAllData) {
        return;
    }
        cd.adderror('Attached files cannot be deleted.');
    }
}


 
Hi There

I want to have a question presented to the user if a field is blank. I understand that ill need a VF page on the record which calls a jquery popup where the user can make the section. The popup would only show if 'field1' is blank, if the users selects yes then it would write yes to field 1, if they select no then it will write no to field 1. I will need to add an if statement to the start of the script.

So far i have made a VF page and put it on the opportunity however the VF page just displays the script in text, it does not execute it. At this stage im just trying to make the popup appear. 

This is a mashup of some scripts if found on here. Any help is appreciated. 

 
<apex:page StandardController="Opportunity">


    <script type="text/javascript" src="/js/functions.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

window.document.onload = new function(e)
<script>
try{
  jQuery(function() {
    /*Append the jQuery CSS CDN Link to the Head tag.*/
    jQuery('head').append('<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/start/jquery-ui.css" type="text/css" />');
    
    /*Create the HTML(DIV Tag) for the Dialog.*/
    var html = 
      '<div id="dialog" title="Question 1 Title"><p>Question 1</p>Some supporting test.</div>';
    
    /*Check if the Dialog(DIV Tag) already exists if not then Append the same to the Body tag.*/
    if(!jQuery('[id=dialog]').size()){
      jQuery('body').append(html);
    }    

    /*Open the jQuery Dialog.*/ 
    jQuery( "#dialog" ).dialog({
      autoOpen: true,
      modal: true,
      show: {
        effect: "highlight",
        duration: 1000
      },
      hide: {
        effect: "fold",
        duration: 200
      },
      buttons: {
        "Yes": function() {
          location.replace('/home/home.jsp');
          jQuery( this ).dialog( "close" );
        },
        "No": function() {
          location.replace('/home/home.jsp');
          jQuery( this ).dialog( "close" );
        },
        Cancel: function() {
          jQuery( this ).dialog( "close" );
        }
      }
    });
  }); 
}
catch(e){
alert('An Error has Occured. Error: ' + e);
}
</script>

</apex:page>

 
Hi All

Im hoping someone can either start me off or point me in the right direction for closing a related opportunity when a contract is activated.
Contracts are activated though an approval flow and unfortunately because of this i cannot build a process in the process builder to close opportunities - it must be done though a trigger.

I understand I need 2 things. 1. The Class which defines what changes need to happen, and 2. The trigger which goes on the contract record to start the class.
 
Where is a good starting point for this?
 
 
 
Hi there
I have a Salesforce site set up, with a number of pages which are accessible without authenticating, i configured this by adding the VisualForce pages to the Site and then clicking on 'Public Access Settings' and made sure that the relevant objects had read (write where required) access. 

It seems that while the object has Read access there is a field which is hidden from the Public user, in searching the forums i can see that i should be able to modify the field level accessibility for the public user in much the same way you do for a normal profile but i cannot seem to find the field level accessibility button on the Public Profile (found by going to the site and clicking on 'Public access settings'). 

How do you change, or view the field level accessibility settings for the public user for the site?

Cheers
​Dale
 
 
 
Hi All

Im trying to alert based on a picklist, my example is below. 
My understanding is that this should work... Is there something im missing?
 
<apex:page StandardController="Opportunity">

    <script>
    
        if({!Opportunity.StageName}=="Contract Signed")
        
            alert('Alert Box');
            
    </script>

</apex:page>

 
Hi All

Full disclosure: Novice at JS.

Im trying to make a button which will check the Region of the Owner and based on that change the Status of the Lead and Change the owner. 
Ive done simmilar things before an im trying to paste it all together but im stuck at the first step! Trying to check the region of the owner.

Is there a way that i can do this? I thoguht just Lead.OwnerId.Region__c would work but clearly not. 

As for the rest of the button im sure there are tons of errors but this is where i need to started i think. 
 
{!REQUIRESCRIPT("/soap/ajax/31.0/connection.js")}

//Define the object
var leadObj = new sforce.SObject("Lead");

//Define the IDs of things
leadObj.Id = '{!Lead.Id}';

// IF APAC
if(('{!Lead.OwnerId.Region__c}' == 'APAC')
	,leadObj.Status = 'Marketing Qualified';  
	leadObj.Owner = '00520000003YH58'; 
	,
	// IF EMEA
	if(('{!Lead.OwnerId.Region__c}' == 'EMEA')
		,leadObj.Status = 'Marketing Qualified';  
		leadObj.Owner = '00520000003YH58'; 
		,
		// IF Americas
		if(('{!Lead.OwnerId.Region__c}' == 'Americas')
			,leadObj.Status = 'Marketing Qualified';  
			leadObj.Owner = '00520000003YH58'; 
			,enter your else-expression here (only for the last one) - 3)))
as 

//update method takes an array of Leads; init to 1 element - 'leadObj'
var result = sforce.connection.update([handObj]);

if (result[0].success == 'false') {
alert(result[0].errors.message);
}

else {
location.reload(true); /* redisplay the detail page */
}

 
Hi All

Ive been playing with the sforce.SingleEmailMessage() ability in SFDC to send an email from a custom object and it works really well with the exception that i cannot see any ability to relate it back to the custom object as an activity.

At the moment the email relates to the contact (amc__Project__c.amc__ContactId__c), which i want it to, but i also want to relate it back to the record where the button is (amc__Project__c.Id). 
Within this documentation i cannot see any reference to linking back to an object which i can see when i click the 'Send an email' link and fill it out manually, ive put a screenshot below of the field im talking about.

Any help is appreciated

JS For the button
{!REQUIRESCRIPT("/soap/ajax/35.0/connection.js")} 

var message = new sforce.SingleEmailMessage(); 



message.replyTo = "{!User.Email}"; 
message.targetObjectId = "{!amc__Project__c.amc__ContactId__c}"; 
message.templateId = "00X5B000000LxrD"; 
message.saveAsActivity = true; 
var result = sforce.connection.sendEmail([message]);

if (result[0].getBoolean("success")) {
    alert("Email Sent");
  } else {
    alert( cResult[0].errors.message);
  }
The field in the send an email button
User-added image
 
Hi All

I have a JS button on a custom object that copies fields from the record an makes a new record in a different object. One of the fields im trying to copy is a long text area but it often has illegal char's and a lot of weird stuff in it.
 
ito.incidentDescription__c = "{!ncident__c.incidentDescription__c }";
Always results in an Illegal error

So im trying to clean it up an put it into an error box so i can confirm that it works but i still get illegal errors. The code im trying that still errors is:
 
{!REQUIRESCRIPT("/soap/ajax/10.0/connection.js")}

var incidentdesc = "{!Incident__c.incidentDescription__c}"
clean = incidentdesc.replace(/[|&;$%@"<>()+,]/g, "");

alert( 
clean
);

Can anyone offer up any possiable solutions to this?

Cheers
Dale
Hi here

I use JS to make an record in an object called 'Incident2op__c' and also update the notes on the incident (TicketMGNT__IncidentHistory__c).
Once an Incident2op__c record is made a process flow takes it and converts it to an opportunity. The problem is that the field 'TicketMGNT__Incident__c.Billing_Work_Type__c' becomes the Incident2op__c's name, and that is then maps to the opporitnity name. So if the Incident2Op name is blank i get a FlowApplication error to my mailbox. The user is unaware and thinks it all went well.

I tried to modify my button like this:
 
{!REQUIRESCRIPT('/soap/ajax/27.0/connection.js')} 
getDate = function(dateObj){ 
var day = dateObj.getDay() < 9 ? '0'+dateObj.getDay() : dateObj.getDay(); 
var month = dateObj.getMonth() < 9 ? '0'+dateObj.getMonth() : dateObj.getMonth(); 

return dateObj.getFullYear()+'-'+month+'-'+day; 
} 

var thedatetime = function xsdDateTime(date) 
{ 
function pad(n) { 
var s = n.toString(); 
return s.length < 2 ? '0'+s : s; 
}; 

var yyyy = date.getFullYear(); 
var mm1 = pad(date.getMonth()+1); 
var dd = pad(date.getDate()); 
var hh = pad(date.getHours()); 
var mm2 = pad(date.getMinutes()); 
var ss = pad(date.getSeconds()); 

return yyyy +'-' +mm1 +'-' +dd +'T' +hh +':' +mm2 +':' +ss; 
} 
var billingworktype = "{!TicketMGNT__Incident__c.Billing_Work_Type__c}"

if(billingworktype != "" && text != null)
{

var ito = new sforce.SObject('Incident2Op__c'); 

ito.Name = '{!TicketMGNT__Incident__c.Name}'; 
ito.OwnerId = '{!User.Id}'; 
ito.Note1__c = "{!TicketMGNT__Incident__c.Invoice_Note__c}" ;
ito.WorkType__c = '{!TicketMGNT__Incident__c.Billing_Work_Type__c}' ;
ito.Category__c = "{!TicketMGNT__Incident__c.TicketMGNT__FKCategory__c	}" ;
ito.LOE__c = "{!TicketMGNT__Incident__c.Estimated_Level_of_Effort__c}" ;
ito.IncidentID__c = '{!TicketMGNT__Incident__c.Name}' ;
ito.CurrencyIsoCode = '{!TicketMGNT__Incident__c.CurrencyIsoCode}' ;
ito.Account__c = "{!TicketMGNT__Incident__c.TicketMGNT__FKAccountId__c}" ;
ito.Incident_Owner__c = '{!TicketMGNT__Incident__c.TicketMGNT__FKOpenById__c}' ;
ito.Price__c = "{!TicketMGNT__Incident__c.Price__c}";
ito.Subject__c = "{!TicketMGNT__Incident__c.Subject__c}" ;
ito.Combined_Total_Duration_Minutes__c = '{!TicketMGNT__Incident__c.Combined_Total_Duration__c}' ;

var inote = new sforce.SObject('TicketMGNT__IncidentHistory__c'); 
inote.Name = '{!TicketMGNT__Incident__c.Name}' ;
inote.TicketMGNT__FKAction__c = 'a0Y20000009ry5LEAQ' ;
inote.TicketMGNT__description__c = 'Billing Opportunity Sent' ;
inote.TicketMGNT__date__c =  thedatetime ;
inote.TicketMGNT__FKUser__c = '{!User.Id}' ;
inote.TicketMGNT__FKIncident__c = '{!TicketMGNT__Incident__c.Id}' ;
inote.TicketMGNT__duration__c = "00:15" ;



result = sforce.connection.create([ito]); 
result = sforce.connection.create([inote]); 

if(result[0].success == 'true'){ 
alert('An New ito - ' + ito.Name + ' was Created Successfully.'); 
} 
else{ 
alert( 
"An Error has Occurred.\r\n The Invoice Note, ELOE, and Billing Work Type must be populated.\r\n" + 
"Error: " + result[0].errors.message 
);
}
else
{
  alert('billingworktype Is Empty');
}

but now nothing happens. The oringal button looked like this:
 
{!REQUIRESCRIPT('/soap/ajax/27.0/connection.js')} 
getDate = function(dateObj){ 
var day = dateObj.getDay() < 9 ? '0'+dateObj.getDay() : dateObj.getDay(); 
var month = dateObj.getMonth() < 9 ? '0'+dateObj.getMonth() : dateObj.getMonth(); 

return dateObj.getFullYear()+'-'+month+'-'+day; 
} 

var thedatetime = function xsdDateTime(date) 
{ 
function pad(n) { 
var s = n.toString(); 
return s.length < 2 ? '0'+s : s; 
}; 

var yyyy = date.getFullYear(); 
var mm1 = pad(date.getMonth()+1); 
var dd = pad(date.getDate()); 
var hh = pad(date.getHours()); 
var mm2 = pad(date.getMinutes()); 
var ss = pad(date.getSeconds()); 

return yyyy +'-' +mm1 +'-' +dd +'T' +hh +':' +mm2 +':' +ss; 
} 



var ito = new sforce.SObject('Incident2Op__c'); 

ito.Name = '{!BMCServiceDesk__Incident__c.Name}'; 
ito.OwnerId = '{!User.Id}'; 
ito.Note1__c = "{!BMCServiceDesk__Incident__c.Invoice_Note__c}" ;
ito.WorkType__c = '{!BMCServiceDesk__Incident__c.Billing_Work_Type__c}' ;
ito.Category__c = "{!BMCServiceDesk__Incident__c.BMCServiceDesk__FKCategory__c	}" ;
ito.LOE__c = "{!BMCServiceDesk__Incident__c.Estimated_Level_of_Effort__c}" ;
ito.IncidentID__c = '{!BMCServiceDesk__Incident__c.Name}' ;
ito.CurrencyIsoCode = '{!BMCServiceDesk__Incident__c.CurrencyIsoCode}' ;
ito.Account__c = "{!BMCServiceDesk__Incident__c.BMCServiceDesk__FKAccountId__c}" ;
ito.Incident_Owner__c = '{!BMCServiceDesk__Incident__c.BMCServiceDesk__FKOpenById__c}' ;
ito.Price__c = "{!BMCServiceDesk__Incident__c.Price__c}";
ito.Subject__c = "{!BMCServiceDesk__Incident__c.Subject__c}" ;
ito.Combined_Total_Duration_Minutes__c = '{!BMCServiceDesk__Incident__c.Combined_Total_Duration__c}' ;

var inote = new sforce.SObject('BMCServiceDesk__IncidentHistory__c'); 
inote.Name = '{!BMCServiceDesk__Incident__c.Name}' ;
inote.BMCServiceDesk__FKAction__c = 'a0Y20000009ry5LEAQ' ;
inote.BMCServiceDesk__description__c = 'Billing Opportunity Sent' ;
inote.BMCServiceDesk__date__c =  thedatetime ;
inote.BMCServiceDesk__FKUser__c = '{!User.Id}' ;
inote.BMCServiceDesk__FKIncident__c = '{!BMCServiceDesk__Incident__c.Id}' ;
inote.BMCServiceDesk__duration__c = "00:15" ;



result = sforce.connection.create([ito]); 
result = sforce.connection.create([inote]); 

if(result[0].success == 'true'){ 
alert('An New ito - ' + ito.Name + ' was Created Successfully.'); 
} 
else{ 
alert( 
"An Error has Occurred.\r\n The Invoice Note, ELOE, and Billing Work Type must be populated.\r\n" + 
"Error: " + result[0].errors.message 
);
}

you can see the changes i made on line 25 where i defined billingwork type
line 27 i made an if statement
line 69/72 i deal with the if statement. 

I hope someone can give me a good lesson on how this should work

Cheers
Dale
Hi All

Please excuse my noviceness here. I have found some blocks of JS which im trying to use for my solution. 
The goal of this is to have a button that the user can click which will prompt them with a popup to provide text, upon providing the text the user will click OK, the text will be placed into 'Reason__c' and the other fields will be updated with the predefined values. 
The record should then save.

So far i have.
 
{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")}

var reason = prompt("Enter reason", "");
if (reason != null) {
    var opportunity = new sforce.SObject("Opportunity");
    opportunity.id = "{!Opportunity.Id}";
    opportunity.StageName = "Closed Lost";
    opportunity.Loss_Reason_Select1__c = "Reason6";
    opportunity.Reason__c = reason;

var result = sforce.connection.update([opportunity]);

if (result[0].getBoolean("success"))
{
    // Refresh window
    window.location.reload();
}
else
{
    alert("Error saving opportunity");
}

Any help or pointers would be grealy appreicated. 

Thanks in advance
Dale 
Hi All

We use an ap within our or that creates users so they can connect though a portal, when these users are made i want to create a contact. The package write the AccountID which the user is associated to into a custom field on the user record, unfortunatly its just text and i cannot use it in the process builder so im trying with an apex trigger. Im getting an error on line 6 where 'for' is mentioned.

I have got an example trigger online but i cannot seem to make it work. If someone could point me in the right direction it would be super. Also keen on any other ideas! :)
 
trigger createAUser on User (after insert) {
    
    List <Contact> ContactInset = new List <Contact> 
    // or whatever your custom object name put instead of Contact
    
    for (User o : Trigger.new) {
        
        
        // here is where you check if User that is being inserted
        // meets the criteria
        //  if (o.Type__c = "X") {  
        
        Contact v = new Contact (); //instantiate the object to put values for future record
        
        // now map User fields to new vehicle object that is being created with this User
        v.FirstName = o.FirstName;
        v.LastName = o.LastName;
        v.Email = o.Email;
        v.Contact_Status__c = "Secondary";
        v.Job_Function__c = "Other";
        v.Job_Level__c = "Administrator";
        v.AccountID = o.AccountId;

        
        //once done, you need to add this new object to the list that would be later inserted. 
        //don't worry about the details for now
        
        ContactInset.add(v);
        
        
        //  }//end if
        
    }//end for o
    
    //once loop is done, you need to insert new records in SF
    // dml operations might cause an error, so you need to catch it with try/catch block.
    try {
        insert ContactInset;    
    } catch (system.Dmlexception e) {
        system.debug (e);
    }
    
}

 
I started to build out a simple trigger from the  to prevent a File record from being deleted from SalesForce Files | Triggers. These file records can be deleted from a related list on a visualforce page. The trigger is active but I can still delete an uploaded File . Any ideas ? 
 
trigger CREContentDocVersion on ContentVersion (before delete) {
for(ContentVersion cv : trigger.old){
        cv.adderror('Document Cannot be deleted');
    }
}

 
Hi There

I want to have a question presented to the user if a field is blank. I understand that ill need a VF page on the record which calls a jquery popup where the user can make the section. The popup would only show if 'field1' is blank, if the users selects yes then it would write yes to field 1, if they select no then it will write no to field 1. I will need to add an if statement to the start of the script.

So far i have made a VF page and put it on the opportunity however the VF page just displays the script in text, it does not execute it. At this stage im just trying to make the popup appear. 

This is a mashup of some scripts if found on here. Any help is appreciated. 

 
<apex:page StandardController="Opportunity">


    <script type="text/javascript" src="/js/functions.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

window.document.onload = new function(e)
<script>
try{
  jQuery(function() {
    /*Append the jQuery CSS CDN Link to the Head tag.*/
    jQuery('head').append('<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/start/jquery-ui.css" type="text/css" />');
    
    /*Create the HTML(DIV Tag) for the Dialog.*/
    var html = 
      '<div id="dialog" title="Question 1 Title"><p>Question 1</p>Some supporting test.</div>';
    
    /*Check if the Dialog(DIV Tag) already exists if not then Append the same to the Body tag.*/
    if(!jQuery('[id=dialog]').size()){
      jQuery('body').append(html);
    }    

    /*Open the jQuery Dialog.*/ 
    jQuery( "#dialog" ).dialog({
      autoOpen: true,
      modal: true,
      show: {
        effect: "highlight",
        duration: 1000
      },
      hide: {
        effect: "fold",
        duration: 200
      },
      buttons: {
        "Yes": function() {
          location.replace('/home/home.jsp');
          jQuery( this ).dialog( "close" );
        },
        "No": function() {
          location.replace('/home/home.jsp');
          jQuery( this ).dialog( "close" );
        },
        Cancel: function() {
          jQuery( this ).dialog( "close" );
        }
      }
    });
  }); 
}
catch(e){
alert('An Error has Occured. Error: ' + e);
}
</script>

</apex:page>

 
Hi All

Im hoping someone can either start me off or point me in the right direction for closing a related opportunity when a contract is activated.
Contracts are activated though an approval flow and unfortunately because of this i cannot build a process in the process builder to close opportunities - it must be done though a trigger.

I understand I need 2 things. 1. The Class which defines what changes need to happen, and 2. The trigger which goes on the contract record to start the class.
 
Where is a good starting point for this?
 
 
 
Hi there
I have a Salesforce site set up, with a number of pages which are accessible without authenticating, i configured this by adding the VisualForce pages to the Site and then clicking on 'Public Access Settings' and made sure that the relevant objects had read (write where required) access. 

It seems that while the object has Read access there is a field which is hidden from the Public user, in searching the forums i can see that i should be able to modify the field level accessibility for the public user in much the same way you do for a normal profile but i cannot seem to find the field level accessibility button on the Public Profile (found by going to the site and clicking on 'Public access settings'). 

How do you change, or view the field level accessibility settings for the public user for the site?

Cheers
​Dale
 
 
 
Hi All

Im trying to alert based on a picklist, my example is below. 
My understanding is that this should work... Is there something im missing?
 
<apex:page StandardController="Opportunity">

    <script>
    
        if({!Opportunity.StageName}=="Contract Signed")
        
            alert('Alert Box');
            
    </script>

</apex:page>

 
Hi All

Full disclosure: Novice at JS.

Im trying to make a button which will check the Region of the Owner and based on that change the Status of the Lead and Change the owner. 
Ive done simmilar things before an im trying to paste it all together but im stuck at the first step! Trying to check the region of the owner.

Is there a way that i can do this? I thoguht just Lead.OwnerId.Region__c would work but clearly not. 

As for the rest of the button im sure there are tons of errors but this is where i need to started i think. 
 
{!REQUIRESCRIPT("/soap/ajax/31.0/connection.js")}

//Define the object
var leadObj = new sforce.SObject("Lead");

//Define the IDs of things
leadObj.Id = '{!Lead.Id}';

// IF APAC
if(('{!Lead.OwnerId.Region__c}' == 'APAC')
	,leadObj.Status = 'Marketing Qualified';  
	leadObj.Owner = '00520000003YH58'; 
	,
	// IF EMEA
	if(('{!Lead.OwnerId.Region__c}' == 'EMEA')
		,leadObj.Status = 'Marketing Qualified';  
		leadObj.Owner = '00520000003YH58'; 
		,
		// IF Americas
		if(('{!Lead.OwnerId.Region__c}' == 'Americas')
			,leadObj.Status = 'Marketing Qualified';  
			leadObj.Owner = '00520000003YH58'; 
			,enter your else-expression here (only for the last one) - 3)))
as 

//update method takes an array of Leads; init to 1 element - 'leadObj'
var result = sforce.connection.update([handObj]);

if (result[0].success == 'false') {
alert(result[0].errors.message);
}

else {
location.reload(true); /* redisplay the detail page */
}

 
Hi All

I have a JS button on a custom object that copies fields from the record an makes a new record in a different object. One of the fields im trying to copy is a long text area but it often has illegal char's and a lot of weird stuff in it.
 
ito.incidentDescription__c = "{!ncident__c.incidentDescription__c }";
Always results in an Illegal error

So im trying to clean it up an put it into an error box so i can confirm that it works but i still get illegal errors. The code im trying that still errors is:
 
{!REQUIRESCRIPT("/soap/ajax/10.0/connection.js")}

var incidentdesc = "{!Incident__c.incidentDescription__c}"
clean = incidentdesc.replace(/[|&;$%@"<>()+,]/g, "");

alert( 
clean
);

Can anyone offer up any possiable solutions to this?

Cheers
Dale
Hi All

Please excuse my noviceness here. I have found some blocks of JS which im trying to use for my solution. 
The goal of this is to have a button that the user can click which will prompt them with a popup to provide text, upon providing the text the user will click OK, the text will be placed into 'Reason__c' and the other fields will be updated with the predefined values. 
The record should then save.

So far i have.
 
{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")}

var reason = prompt("Enter reason", "");
if (reason != null) {
    var opportunity = new sforce.SObject("Opportunity");
    opportunity.id = "{!Opportunity.Id}";
    opportunity.StageName = "Closed Lost";
    opportunity.Loss_Reason_Select1__c = "Reason6";
    opportunity.Reason__c = reason;

var result = sforce.connection.update([opportunity]);

if (result[0].getBoolean("success"))
{
    // Refresh window
    window.location.reload();
}
else
{
    alert("Error saving opportunity");
}

Any help or pointers would be grealy appreicated. 

Thanks in advance
Dale 
Hi All

We use an ap within our or that creates users so they can connect though a portal, when these users are made i want to create a contact. The package write the AccountID which the user is associated to into a custom field on the user record, unfortunatly its just text and i cannot use it in the process builder so im trying with an apex trigger. Im getting an error on line 6 where 'for' is mentioned.

I have got an example trigger online but i cannot seem to make it work. If someone could point me in the right direction it would be super. Also keen on any other ideas! :)
 
trigger createAUser on User (after insert) {
    
    List <Contact> ContactInset = new List <Contact> 
    // or whatever your custom object name put instead of Contact
    
    for (User o : Trigger.new) {
        
        
        // here is where you check if User that is being inserted
        // meets the criteria
        //  if (o.Type__c = "X") {  
        
        Contact v = new Contact (); //instantiate the object to put values for future record
        
        // now map User fields to new vehicle object that is being created with this User
        v.FirstName = o.FirstName;
        v.LastName = o.LastName;
        v.Email = o.Email;
        v.Contact_Status__c = "Secondary";
        v.Job_Function__c = "Other";
        v.Job_Level__c = "Administrator";
        v.AccountID = o.AccountId;

        
        //once done, you need to add this new object to the list that would be later inserted. 
        //don't worry about the details for now
        
        ContactInset.add(v);
        
        
        //  }//end if
        
    }//end for o
    
    //once loop is done, you need to insert new records in SF
    // dml operations might cause an error, so you need to catch it with try/catch block.
    try {
        insert ContactInset;    
    } catch (system.Dmlexception e) {
        system.debug (e);
    }
    
}