1

I have two picklists ...a controlling and its dependent.On button click I am trying to get its values in a javascript variables.The problem is I am able to see the controlling picklist selected value but dependent picklist value is "undefined".This same code working good for other controlling/dependent picklist.

//VF code

<apex:page controller="STBPicklistUpdateController" id="Pageid">
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
    <apex:form id="formId">              
         STB Product ://**Controlling picklist
         <apex:inputField value="{!STBSoftware.STB_Product__c}"  id="stbId" styleClass="contstb"/>              
         Sub Product : //** first dependent picklist
         <apex:inputField value="{!STBSoftware.Sub_Product__c}"  id="subId" styleClass="contstb-dep" />           
         S/W Version //**Second dependent picklist
         <apex:inputField value="{!STBSoftware.Software_Version__c}"   styleClass="contstb dep2"/>     
         Enter Value :<apex:inputText styleClass="new-dep-data"/> &nbsp; 
        <div align="left">                
            <input type = "button" value="Add Data" class="add-btn"/>
        </div><br/><br/>              
    </apex:form> 

    <script language="javascript" type="text/javascript"> 
       $(document).ready(function() {
           $('body').on('click', '.add-btn', function() {

               var cVal = $('.contstb-dep').val();
               alert(cVal); //**undefined 

               var depVal = $('.new-dep-data').val();
               alert(depVal);

               if (cVal == '') {
                   alert('Please Select sub product');
                   return false;
               } else if (depVal == '') {
                   alert('Please Enter value in text box..');
                   return false;
               } else {

                   Visualforce.remoting.Manager.invokeAction(
                       '{!$RemoteAction.STBPicklistUpdateController.UpdateDependentPicklistadd}',
                       cVal, depVal,
                       function(result, event) {
                           if (result == 'Done') {
                               alert('Value added');
                               window.location.reload(true);
                           }

                       }
                   );
               }
           });
       });
    </script>    
    </apex:page>

//controller code

public with sharing class STBPicklistUpdateController {

    public STB_Software__c STBSoftware {
        get;
        set;
    }

    public STBPicklistUpdateController() {
        STBSoftware = new STB_Software__c();
    }

    public static MetadataService.MetadataPort createService() {
        MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = UserInfo.getSessionId();
        return service;
    }

    @RemoteAction
    public static String UpdateDependentPicklistadd(String controlFieldVal, String depFieldVal) {
        try {
            MetadataService.MetadataPort service = createService();
            MetadataService.CustomField customField = (MetadataService.CustomField) service.readMetadata('CustomField',
            new String[] {
                'STB_Software__c.Software_Version__c'
            }).getRecords()[0];
            system.debug('customField----' + customField);
            metadataservice.Picklist pt = new metadataservice.Picklist();
            pt.sorted = false;
            pt.controllingField = 'Sub_Product__c'; //***** name of controlling field . if picklist has contrlloing field , this must be asssigned . else field dependency will be deleted
            metadataservice.PicklistValue first_dependent = new metadataservice.PicklistValue();
            first_dependent.fullName = depFieldVal;
            first_dependent.default_x = false;
            first_dependent.controllingFieldValues = new list < string > {
                controlFieldVal
            }; // list of names of controlling field Picklist value . dont put this line , if you dont want any controlling picklist value
            pt.picklistValues = new list < metadataservice.PicklistValue > {
                first_dependent
            };
            customField.picklist.picklistValues.add(first_dependent);
            handleSaveResults(
            service.updateMetadata(
            new MetadataService.Metadata[] {
                customField
            })[0]);
        } catch (exception e) {
            system.debug('caught exception');
        }
        return 'Done';
    }

    public class MetadataServiceExamplesException extends Exception {}
    public static void handleSaveResults(MetadataService.SaveResult saveResult) {
        // Nothing to see?
        if (saveResult == null || saveResult.success) return;
        // Construct error message and throw an exception
        if (saveResult.errors != null) {
            List < String > messages = new List < String > ();
            messages.add(
            (saveResult.errors.size() == 1 ? 'Error ' : 'Errors ') +
                'occured processing component ' + saveResult.fullName + '.');
            for (MetadataService.Error error: saveResult.errors)
            messages.add(
            error.message + ' (' + error.statusCode + ').' + (error.fields != null && error.fields.size() > 0 ?
                ' Fields ' + String.join(error.fields, ',') + '.' : ''));
            if (messages.size() > 0) throw new MetadataServiceExamplesException(String.join(messages, ' '));
        }
        if (!saveResult.success) throw new MetadataServiceExamplesException('Request failed with no specified error.');
    }

} //end of class
1
  • Can you please share the controller code?
    – Saroj Bera
    Aug 3, 2015 at 8:19

2 Answers 2

0

I was able to find the work around solution this dependent variable is undefined problem...

Created a textbox on Vf page:

<apex:inputText id="newtxt" styleClass="new-text-data" html-readonly="true" />

and set it hidden at the load of the page:

   $(document).ready(function(){ 
        $('.new-text-data').hide();
   });

Then Created a function which captures a value of a dependent picklist and assigning this to textbox created above

   <apex:inputField value="{!c.Sub_Product__c}" styleClass="dep-sub-pro" onchange="myFunction(this);" /> 

<script>
    function myFunction(sel)
    {
        var d = sel.options[sel.selectedIndex].text;
        $('.new-text-data').val(d);

    }
</script>

and now passing its value to VF remoting method

 var depVal = $('.new-dep-data').val();

 Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.PickListUpdateController.UpdatePicklistAndRecordType}',
            cVal,depVal,

I still not sure why it was undefined..

-1

Try using apex:action support on onchange of STB_Product and rerender Sub_Product. You need to code in the controller for this.

1
  • Hi Goki,I need to pass these picklist values to controller via javascript remoting.I have edited the above code..
    – ver123
    Aug 4, 2015 at 18:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .