2

I have a VF page set up for users to enter one or more Opportunity Products from a custom search. I also have a script set up to default the Quantity field to "1". The problem I am running into is that if a user changes the Quantity to anything but "1", when a new product is added to the list my VF page ReRenders and the value of the Quantity is then reset back to "1". Does anyone know how I can update my script to populate "1" if the Quantity field is empty and use the value already entered in the Quantity field if it is not empty?

VF Line:

<apex:inputField value="{!s.Quantity}" style="width:70px" required="true" id="qty">
    <script>
        document.getElementById('{!$Component.qty}').value = 1;
    </script>
</apex:inputField>
  • 1
    What is "refreshTotals"? – sfdcfox May 31 '17 at 17:20
  • Sorry, that is extraneous code that I had in there but changed. I updated my post. – John Neilan May 31 '17 at 17:25
3

When you reRender an area with a script block, the script gets run again. This means that it'll always reset the value back to 1. As such, you should probably check its value first:

<apex:inputField value="{!s.Quantity}" style="width:70px" required="true" onkeyup="refreshTotals();" id="qty">
    <script>
        if(!document.getElementById('{!$Component.qty}').value) {
            document.getElementById('{!$Component.qty}').value = 1;
        }
    </script>
</apex:inputField>

This isn't the only way to do it, but is the method that would require the least amount of effort from where your code is right now.

1

There's not enough code here to determine the issue. My hunch is that refresh totals includes a call to an action method that contains a rerender attribute referencing a parent element of this field. When you combine that with your JS you are guarenteeing the field will be set back to 1. There's about a dozen ways to set the default value of the field to 1 without using JS.

For instance, when you instantiate the object within the controller for the first time, you can set it to 1 within the controller so that it appears as 1 by default. That should set the default to 1 only on page load only, unless you set it in the same method you call when you rerender (which would be silly).

Here is a rough example:

Apex Class

public class pageController {
    public OpportunityLineItem s {
        get {
            if (s == null) {
                s = new OpportunityLineItem();
                s.quantity = 1;
            }

            return s;
        }

        set;
    }
}

One of the issues I see most common in new SF devs is that they are more fammiliar with Javascript then apex/visualforce and default to JS to accomplish tasks in the way that they're used to/understand. In this case, JS is not the answer.

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.