Home > database >  How can I pass value as GET through a hyperlink?
How can I pass value as GET through a hyperlink?

Time:01-31

I have two entities - Budget and Income. On the "view budget" page I have this hyperlink, from where the user can create an income to that specific budget:

<a href="{{ path('app_income_new', { 'budget': budget.id }) }}">Create income to this budget</a>

// Result: /income/new?budget=1

// What I want: /income/new

Is it possible somehow to remove ?budget=1 and still pass on the budget.id as a POST variable value so the hyperlink becomes short: /income/new?

CodePudding user response:

You cant pass post parameters with an anchor

You could use a form though, sth like:

<form action="{{ path('app_income_new') }}" method="POST">
  <input type="hidden" name="budget" value="{{ budget.id }}">
  <input type="submit" value="Create income to this budget">
</form>

should do the trick, maybe add some css to make it "look like a link"

CodePudding user response:

In order to have this behavior with just an actual anchor <a> element you need to use a javascript event listener to build and submit a form element when the anchor is clicked. You can insert the related data (path & budget.id) into data attributes of the anchor. The event listener can access the data of the clicked anchor (so you can have many with different datasets). Below is a configurable example that can support additional fields by adding the field name where noted, and the appropriate data attribute.

const postAnchors = document.querySelectorAll(".post-link");
postAnchors.forEach((anchor) => {
  anchor.addEventListener('click', function(e) {
    const fields = [
      'budget',
      // to support additional fields add here
    ]
    const form = document.createElement('form')
    fields.forEach(field => {
      if (anchor.dataset[field]) {
        const input = document.createElement('input')
        input.name = field
        input.type = 'text'
        input.value = anchor.dataset[field] // data-{field} value
        form.append(input)
      }
    })

    form.method = 'post'
    form.action = anchor.dataset.action
    document.querySelector('body').append(form)
    form.submit()
  })
})
<a href="#"  data-action="{{ path('app_income_new') }}" data-budget="{{ budget.id }}">Create income to this budget</a>

  • Related