1

I am trying to get the id of contacts from accounts using Javascript.But seems like something is not right in the code, which has to alert the ids one by one. Here is my visualforce and extension code:

VF page:

<apex:page standardController="Account" extensions="testjavascriptextension">

  <script>

  var theControllerValue = '{!cnt}';
  sample();

  function sample(){
  for(int i=0;i<theControllerValue.size();i++)
  {
  alert('this is ' + i + 'th value ' + theControllerValue[i]);
  }
  }


  </script>

</apex:page>

Controller Extension:

public class testjavascriptextension {


    public Account acct{get;set;}
    public List<Contact> cnt{get;set;}

    public testjavascriptextension(ApexPages.StandardController controller) {
    this.acct= (Account)controller.getRecord();
    cnt=[select name,id from contact where contact.account.id=:acct.id];
    }

}

Not sure why I am not seeing any alert on the page.

2
var theControllerValue = '{!cnt}';<br>
theControllerValue = theControllerValue .toString();<br>
theControllerValue = theControllerValue .replace('[','');<br>
theControllerValue = theControllerValue .replace(']','');<br>
var arraylist = theControllerValue .split(",");<br>
alert(arraylist[0]);

The code itself is self explanatory have written in very easy form. Hope it works for you. Thank you

4

You have some JavaScript issues. There's no size() function in JavaScript arrays and no types like int. Try below for loop in you javascript instead of yours.

for(var i=0;i<theControllerValue.length;i++)
{
    alert('this is ' + i + 'th value ' + theControllerValue[i]);
}

Also note that your cnt variable might not have values when you refer it in this way as per the order of loading. I'm not sure about that and need to try it out.

  • Thanks. I have a issue here. I am trying to alert only the id's here but what I get is each character of the id is getting alerted, how can I get the 15 digit id to be alerted here? – SfdcBat May 29 '16 at 10:10
  • That's again about JavaScript, try alert(theControllerValue[i].id); inside the loop – highfive May 29 '16 at 10:18
  • That says 'this is 0 th value undefined, for all the i values in for loop it says undefined. When I alert out the variable theControllerValue , I get -> [ 0000werthfbgncd , 0000ruejdkfjsfj] .. these are ids of the contacts associated with the accounts. I want to grab each id and alert it. Is it possible? – SfdcBat May 29 '16 at 10:22
  • 1
    Try Id instead of id. JavaScript is case sensitive – Phil B May 29 '16 at 11:25
2

'{!cnt}' is a string, so you can put it into an array and loop through it as so.

// Create an array
var contactIds = '{!cnt}'
            .replace('[','')
            .replace(']','')
            .split(',');
// Loop through it
for (var i = 0; i < contactIds.length; i++) {
    // Alert the id
    alert(contactIds[i]);
}

But all you will get is the the Id. It's best to use JavaScript Remoting in case you need more than the Id.

<apex:page standardController="Account" extensions="testjavascriptextension">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"/>
<script>
var recordId='{!$CurrentPage.Parameters.id}';
// Check to see if their is an Id to ensure you have an account Id
if (recordId !== '') {
    // Create array 
    var contactIds = '{!cnt}'
        .replace('[','')
        .replace(']','')
        .split(',');
    // Loop through it
    for (var i = 0; i < contactIds.length; i++) {
        // Alert the Id
        alert(contactIds[i]);
    }
    Visualforce.remoting.Manager.invokeAction('testjavascriptextension.getContacts',
        recordId,                                      
        function(result, event) {
            if (event.status) {
                console.log(result);
                // JavaScript - loop through the contacts
                for (var i = 0; i < result.length; i++) {
                    // Get the Id
                    console.log(result[i].Id);
                    // Get the name too
                    console.log(result[i].Name);
                    // alert(result[0].Id);
                    // alert(result[0].Name);
                }
                // jQuery
                $.each(result, function(index, contact) {
                    // Get the Id
                    console.log(contact.Id);
                    // Get the name too
                    console.log(contact.Name);
                    // alert(contact.Id);
                    // alert(contact.Name);
                });

            } else {
                console.log(event.message);
            }
        }, {
        escape: true
    });                 
}
</script>

Controller:

global class testjavascriptextension {

    public Account acct{get;set;}
    public List<Contact> cnt{get;set;}

    public testjavascriptextension(ApexPages.StandardController controller) {
        this.acct= (Account)controller.getRecord();
        cnt=[select name,id from contact where contact.account.id=:acct.id];
    }

    @RemoteAction
    global static List<Contact> getContacts(String acctId) {
        return [select name, id from contact where contact.account.id =:acctId];
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.