putyourlightson / craft-sprig

A reactive Twig component framework for Craft CMS.
https://putyourlightson.com/plugins/sprig
MIT License
124 stars 9 forks source link

Communicating between nested Components #353

Closed shifuma closed 6 months ago

shifuma commented 6 months ago

Hi Ben,

I have a setup like this:

## index.twig
{{ sprig('games') }}

## games.twig
## all sorts of filters but also a nested Sprig Component Class:
{{ sprig('reports') }}

Reports is doing some more advanced calculations and returning an array of entry IDs. This works fine, however, I'm having a hard time passing those back up the chain to the main component.

I've tried a few combinations of things like {'s-listen': 'reports'} / {'id': 'reports'} and s-replace etc, but without any success. Is something like this possible? Hopefully I'm just missing something simple, as I often do.

Thank you in advance for looking at this.

Edit: I found a number of similar-ish issues and even the docs on this, but they seem to be focussed on passing down data the chain, rather than up.

bencroker commented 6 months ago

What's the reason for nesting components here? Is it because reports should be refreshable independently of games?

If so, then the simplest way to achieve this is to use htmx.trigger as per the second approach in https://putyourlightson.com/sprig/cookbook#refreshing-components

shifuma commented 6 months ago

Here's one thing I tried:

## index.twig
{{ sprig('games', {}, {'id': 'games') }}

## games.twig
{{ sprig('reports') }}

## reports.twig -- I'm setting $this->success in my component class
{% if success is defined and success == true %}
  <script>
    htmx.trigger('#games', 'refresh');
  </script>
{% endif %}

Which seems to refresh the component but the IDs from reports aren't available in games.

bencroker commented 6 months ago

You didn’t answer my question, but you’ll likely need to put those IDs into an input field that the parent component will then be able to access via the input field name. For example:

{{ hiddenInput('entryIds', entryIds) }}
shifuma commented 6 months ago

Sorry, it looks like we commented at pretty much the same time and I missed the first reply. The hiddenInput is exactly what I needed, thanks!

What's the reason for nesting components here? Is it because reports should be refreshable independently of games?

Just to answer this for context in case others see the issue, I have some pre-built reports that I want to apply to 'games'. Then I want to allow users to further filter those results with the main component.