+ Start a Discussion
Abhilash DaslalAbhilash Daslal 

Use a dynamic SOQL inside a VF component

I have controller class where I am using a dynamic query as shown below

  String query = 'SELECT ' +  newsletterField + ' FROM Contact WHERE Id = ' + user_id;
  Contact[] myContacts = Database.query(query);

How to include the dynamic query inside a Visualforce Component and the same Visualforce component is later used in a VF page

Om PrakashOm Prakash
You can use SOQL query in visualforce page inside Script.
Below component is an example for your use case. Let me know if still any query.

Visuslforce Component Name = SQLQuery
  <script src="/soap/ajax/30.0/connection.js"></script >
    sforce.connection.sessionId = '{!$Api.Session_ID}';
    var contactId = ''; // Put your contact id here or get it dynamically from parameters
    var newsletterField = 'Name'; // Update with your newsletterField api name
    var result = sforce.connection.query('SELECT ' +  newsletterField + ' FROM Contact WHERE Id = \'' + contactId + '\'');
    var records = result.getArray("records");
    for (var i=0; i< records.length; i++) {
      var record = records[i];
      console.log('Contact Name: ' + record.get(newsletterField));
Visuslforce Page:
<apex:page >
  <c:SQLQuery />