[SalesForce] Getting an Opportunity Id into a Visualforce page when clicking a list button on a related list

I'm currently trying to make a system for selecting multiple objects and connecting them to a related list within Opportunities.

The last piece of the puzzle for me is getting the ID of the opportunity.

Since this will be a list button I can't treat it like a scenario and just use {!JunctionObject.Opportunity} as that returns as a null entity.

Alternatively if anyone has any ideas on how to more efficiently do this it would be greatly appreciated.

APEX values

Custom Object: Package__c

Junction Object: Opportunity_Package__c

Junction Objects reference to the Opportunity: Opp_Package_Rel__c

Visualforce Code

<apex:page standardController="Opportunity_Package__c" extensions="MetadataPackageEditor" recordSetVar="Opportunity_Package__c" sidebar="false" showHeader="false">
  <apex:form >
      <apex:pageBlock title="Select Package(s)">
      <apex:pageMessages />

          <apex:pageBlockTable value="{!packages}" var="o" id="table">
              <apex:column >
                  <apex:inputCheckbox value="{!o.selected}"/>
              </apex:column>
              <apex:column value="{!o.pack.Name}"/>
              <apex:column value="{!o.pack.Products__c}"/>
              <apex:column value="{!o.pack.PPU_Discount__c}"/>
          </apex:pageBlockTable>
      <apex:commandButton value="Add Packages"/>
      <apex:commandButton action="{!cancel}" value="Cancel"/>
      </apex:pageBlock>
  </apex:form>
</apex:page>

Best Answer

If you are Ok to create VF page then you can create a Custom Button on Opportunity page and clicking will open VF page which will show List View of "Opportunity Package" with ability to select records using checkbox.

Back to your question, You can use document.referrer in Javascript code to check Previous page URL and extarct Opportunity URL, However this approach will not work if user comes from non opportunity record.

How to use Javascript to get previous Page URL in Visualforce?

We can Use Hidden field, myString is STring variable in Controller

<apex:inputHidden value="{!myString}" id="myHiddenField"/>

On Page Load event, we can do something like this :

<script>
var StrArray = document.referrer.split('/');
var OppId = StrArray[StrArray.length-1]
document.getElementById("{!$Component.myHiddenField}") = OppId  ;
</script>

You can use this article on how to get element ID in Visualforce.