Jump to content
dadish

GraphQL for ProcessWire

Recommended Posts

1 hour ago, DavidBerlin said:

Children results work with "name" instead of "title"...

The children results only have with built-in page fields. They don't have template fields. You have to make sure the field title exists in GraphiQL before querying it. When you go to Setup -> GraphQL and enter the above query it will tell you that there is no "title" field for children list. If the field is not in your GraphQL schema you cannot query it.

If you want to query your task pages with template fields like title, you can set them as a Page field like you do with your job_client field. That way your tasks will have all the template fields you enabled.

  • Like 2

Share this post


Link to post
Share on other sites

dadish,

First, thank you for this wonderful module, it's been awesome working with GraphQL.

The problem: I have a field where the type is "Page Reference" and the input field type is "Page Auto Complete". In the details tab, the "Multiple pages PageArray" is selected.

If I only have one page reference, then it will return the result as expected using the "list". However, if I have multiple page references, then it will not display any results at all. Can you let me know if there is something I am doing wrong or is this is a bug/feature that needs to be worked?

All the best!

  • Like 1

Share this post


Link to post
Share on other sites

Hello @Brett.

Thank you for your feedback! I was able to reproduce your issue and hopefully tracked down the bug. Please, install the latest version and give it a try. Let me know if the issue is resolved for you.

New Release 1.1.3

- Fixed bug with FieldtypePage returning only single value.

  • Like 6

Share this post


Link to post
Share on other sites

Hi @dadish,

I'm upgrading a site to use the latest version of this module.

I'm having trouble with a page reference field when creating a new page with a mutation.

Before, I was using a mutation with variables like this:

mutation ($page: ConfiguratorQuoteUpdateInput!) {
  createConfiguratorQuote(page: $page) {
    id
  }
}

variables: {
  "page": {
    "name": "test-quote",
    "title": "Tets Quote",
    "parent": "22905",
    "colour": [10392] // this is the page reference field
  }
}

I noticed the field now uses the type InputfieldPage rather than [ID] and there are add and remove fields inside this InputfieldPage field.

I have tried formatting the variables in a couple of ways and I see this error in graphqil:

// "debugMessage": "Method NullPage::add does not exist or is not callable in this context",

// When using either of these

variables: {
  "page": {
    "name": "test-quote",
    "title": "Test Quote",
    "parent": "22905",
    "colour": {
      "add": 10392
    }
  }
}

variables: {
  "page": {
    "name": "test-quote",
    "title": "Test Quote",
    "parent": "22905",
    "colour": {
      "add": [10392]
    }
  }
}

Can you advise how I should be adding page reference fields? I have checked the page template and fields are legal, they return without issue in queries for existing pages.

 

Many thanks,

Tom

  • Like 1

Share this post


Link to post
Share on other sites

@sodesign

First, I want to clarify some stuff. You are saying that you want to create a page and using a mutation field "createConfiguratorQuote" but supplying it with "ConfiguratorQuoteUpdateInput" which is an incorrect input type. You should supply "ConfiguratorQuoteCreateInput" for creating and "ConfiguratorQuoteUpdateInput" for updating a page.

The "add" and "remove" for page references always expects an array of ids. So your latest format for variables is correct for creating a page. Just change UpdateInput type to CreateInput type.

But, if you're trying to update a page then "page" input variable should include "id" field. It should look like this...

variables: {
  "page": {
    "id" : 11111, // <=== you should tell which page you're trying to update.
    "name": "test-quote",
    "title": "Test Quote",
    "parent": "22905",
    "colour": {
      "add": [10392]
    }
  }
}

Let me know if I'm missing something.

  • Like 2

Share this post


Link to post
Share on other sites

Sorry - copy and paste error*. I am using a ConfiguratorQuoteCreateInput field when I get the error.

*(I tried using update as well in case the page reference needed a parent page to exist first)

 

  • Like 1

Share this post


Link to post
Share on other sites

@sodesign

Ok, I think I found the problem. I was able to get the same error as yours and patched the module to fix it, just now. Try the latest version and let me know if the issue is resolved for you.

New Release 1.1.4

- Fix FieldtypePage bug when FieldtypePage:derefAsPageOrNullPage option is enabled.

  • Like 3

Share this post


Link to post
Share on other sites
On 1/15/2020 at 6:53 AM, dadish said:

Hello @Brett.

Thank you for your feedback! I was able to reproduce your issue and hopefully tracked down the bug. Please, install the latest version and give it a try. Let me know if the issue is resolved for you.

New Release 1.1.3

- Fixed bug with FieldtypePage returning only single value.

I can confirm that 1.1.4 fixed the issue we were having. Thank you for getting back so quickly. 🙂

  • Like 1

Share this post


Link to post
Share on other sites

  

14 hours ago, dadish said:

@sodesign

Ok, I think I found the problem. I was able to get the same error as yours and patched the module to fix it, just now. Try the latest version and let me know if the issue is resolved for you.

New Release 1.1.4

- Fix FieldtypePage bug when FieldtypePage:derefAsPageOrNullPage option is enabled.

Just updated and the issue is fixed, thank you for such a speedy patch!

  • Like 1

Share this post


Link to post
Share on other sites

One other small thing - can you add support for the built in 'title' field in the Page type? 

I tried this locally editing the getBuiltInFields() function at line 41 in src/Type/PageType.php

Thanks,

Tom

  • Like 1

Share this post


Link to post
Share on other sites
On 12/13/2019 at 4:11 PM, dadish said:

The children results only have with built-in page fields.

I have one more question - do you plan to include child template fields?

If not, what is your recommendation for querying child pages?

Thanks

Share this post


Link to post
Share on other sites
On 1/17/2020 at 9:36 PM, sodesign said:

One other small thing - can you add support for the built in 'title' field in the Page type? 

I tried this locally editing the getBuiltInFields() function at line 41 in src/Type/PageType.php

I understand why you are asking for this feature. You're not the first one. But it's not as obvious as it seems. The 'title' field is not the same as all other built-in fields. You can't modify the behavior of the built-in fields per template basis. Which means they all behave the same no matter what template the page has. That's why we have a generic type 'Page' that has all the built-in fields. No matter what template the page we can confidently serve those fields for every page.

The 'title' field's behavior could change depending on the template. I understand that it is almost never the case, but semantically it is. For example, you can set different access settings for 'title' field depending on the template. You make it that user can view the 'title' on one template and not on the other. You can change the description of the field for each template and it will appear in the GraphQL documentation. You can also make 'title' field 'not required' for one template and 'required' for others.

So, including 'title' field into the Page type will break the semantics. I understand that 'title' field is almost always treated as a built-in field but I just can't overcome this feeling that it is the 'wrong' way to do it. I would like do it only the 'right' way. And the right way brings us to your second question.

22 hours ago, sodesign said:

I have one more question - do you plan to include child template fields?

If not, what is your recommendation for querying child pages?

If we implement it properly and add the ability to get the values of the template fields for generic Page types, then 'title' field should also be solved. For this we will be adding interfaces. It will allow you to get template fields for Page types by providing a template. It will look something like this.

{
  city{
    list{
      children{ # <== let's say children are the pages with template skyscraper and architect
        list{
          id
          name
          ... on SkyscraperPage { # <== you basically say: "for skyscraper pages give me these fields"
            title
            images{
              url
              width
              height
            }
          }
          ... on ArchitectPage { # <== "and for architect pages give me these fields"
            born
            email
            resume{
              url
              filesize
            }
          }
        }
      }
    }
  }
}

this way you can fetch values for all template fields on Page types. This will work with everything that returns a Page type. Including 'child', 'children', 'parent', 'parents' and Page Reference fields too. And the best part is, it will be semantically correct! 😄

  • Like 5

Share this post


Link to post
Share on other sites

Thank you for explaning these details and your plans.

If you'd like any help testing, I'd be happy to do what I can; this module is a great asset for PW develoment.

  • Like 2

Share this post


Link to post
Share on other sites

Hi! I'm getting this error when I post to /graphql:

{
    "errors": [
        {
            "message": "Syntax Error: Unexpected <EOF>",
            "extensions": {
                "category": "graphql"
            },
            "locations": [
                {
                    "line": 1,
                    "column": 1
                }
            ]
        }
    ]
}

I'm using POST with Content-Type: application/json and the post body looks like this:

{
	"query": "{ integrante { title } }"
}

When I try with GraphiQL (which posts to /processwire/setup/graphql instead of /graphql), everything works perfectly. Of course the templates are installed, field and templates access are configured, etc.

I've tried using a public GraphQL API like https://countries.trevorblades.com/ and it works fine.

What am I doing wrong? I've tried manually from Postman and also using Gatsby's gatsby-source-graphql plugin. Both get the same <EOF> error.

It's a new blank ProcessWire installation, master branch. Please help! Thanks in advance!

Share this post


Link to post
Share on other sites
On 3/7/2020 at 7:19 AM, Miguel Scaramozzino said:

When I try with GraphiQL (which posts to /processwire/setup/graphql instead of /graphql), everything works perfectly. Of course the templates are installed, field and templates access are configured, etc.

Can you post the code in your graphql.php template file. My only guess is that something happening in that file.

  • Like 1

Share this post


Link to post
Share on other sites
On 3/8/2020 at 1:19 PM, dadish said:

Can you post the code in your graphql.php template file. My only guess is that something happening in that file.

Here it is:

<?php namespace ProcessWire;

header('Content-Type: application/json');

echo json_encode($modules->get('ProcessGraphQL')->executeGraphQL(), true);

 

Share this post


Link to post
Share on other sites

Here's something interesting, I've created a /test.php file with the following code:

<?php
namespace ProcessWire;

require("index.php");

header('Content-Type: application/json');

echo json_encode($modules->get('ProcessGraphQL')->executeGraphQL(), true);

This works fine.

So there must be something wrong with the way that the graphql template is being processed. Maybe ProcessWire is taking control of the post body before it reaches the module and this doesn't happen when you bootstrap PW from an external file?

  • Like 1

Share this post


Link to post
Share on other sites
12 hours ago, Miguel Scaramozzino said:

So there must be something wrong with the way that the graphql template is being processed. Maybe ProcessWire is taking control of the post body before it reaches the module and this doesn't happen when you bootstrap PW from an external file?

In your graphql template file. Try manually extracting the query and variables and passing them to ProcessGraphQL. Should looks something like this.

<?php

namespace ProcessWire;

header('Content-Type: application/json');

$query = $input->post->query;
$variables = $input->post->variables || [];

echo json_encode($modules->get('ProcessGraphQL')->executeGraphQL($query, $variables), true);

It might be slightly different how you extract the query but the bottom line is make sure you're getting it in your graphql template file and passing it to ProcessGraphQL.

Share this post


Link to post
Share on other sites
13 hours ago, dadish said:

It might be slightly different how you extract the query but the bottom line is make sure you're getting it in your graphql template file and passing it to ProcessGraphQL.

Yes, this is the problem clearly. I've tried $input->post->query but that won't work cause it's not form-data but a json body. So I've tried file_get_contents("php://input") and it comes up empty. There must be something wrong with my PW installation, cause I've created REST APIs in the past parsing json data from php://input with no issues at all. I will try to downgrade the PW core and see what happens.

Share this post


Link to post
Share on other sites

BTW my /test.php file receives the php://input contents just fine. That's why the module has no problem parsing it when loaded from outside the PW template system. This is weird. I guess it's now a question for Ryan.

Share this post


Link to post
Share on other sites
21 minutes ago, Miguel Scaramozzino said:

Yes, this is the problem clearly. I've tried $input->post->query but that won't work cause it's not form-data but a json body. So I've tried file_get_contents("php://input") and it comes up empty. There must be something wrong with my PW installation, cause I've created REST APIs in the past parsing json data from php://input with no issues at all. I will try to downgrade the PW core and see what happens.

Make sure you check nginx/apache and PHP logs as well. If memory serves me correctly, I had a similar issue do to something was blocking because of XSS. There was a server change I had to make, so keep a close eye on those logs and the developer tools on your browser.

Share this post


Link to post
Share on other sites

@Miguel Scaramozzino Also, just wanted to confirm with you that you're making request to the correct url. In default PW settings "/graphql" and "/graphql/" are different. If you happen to make a request to "/graphql" (without forward slash at the end) it will be redirected to "/graphql/" and the content of your POST request gets lost in the middle.

  • Like 1
  • Thanks 1

Share this post


Link to post
Share on other sites
2 hours ago, dadish said:

@Miguel Scaramozzino Also, just wanted to confirm with you that you're making request to the correct url. In default PW settings "/graphql" and "/graphql/" are different. If you happen to make a request to "/graphql" (without forward slash at the end) it will be redirected to "/graphql/" and the content of your POST request gets lost in the middle.

You are absolutely right sir! Adding the final slash fixes it. I've been using PW for years and I've never encountered that quirk. Thanks a lot!

Share this post


Link to post
Share on other sites
18 hours ago, Miguel Scaramozzino said:

I've been using PW for years and I've never encountered that quirk.

For some reason this is an issue only with this module. You're not the first one to stumble on it. I updated the Readme to add Troubleshooting section that explains this issue in details.

  • Like 1

Share this post


Link to post
Share on other sites

Thank you for this module! It best for my mobile apps!

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By bernhard
      --- Please use RockFinder3 ---
    • By MoritzLost
      Cacheable Placeholders
      This module allows you to have pieces of dynamic content inside cached output. This aims to solve the common problem of having a mostly cacheable site, but with pieces of dynamic output here and there.  Consider this simple example, where you want to output a custom greeting to the current user:
      <h1>Good morning, <?= ucfirst($user->name) ?></h1> This snippet means you can't use the template cache (at least for logged-in users), because each user has a different name. Even if 99% of your output is static, you can only cache the pieces that you know won't include this personal greeting. A more common example would be CSRF tokens for HTML forms - those need to be unique by definition, so you can't cache the form wholesale.
      This module solves this problem by introducing cacheable placeholders - small placeholder tokens that get replaced during every request. The replacement is done inside a Page::render hook so it runs during every request, even if the response is served from the template cache. So you can use something like this:
      <h1>Good morning, {{{greeting}}}</h1> Replacement tokens are defined with a callback function that produces the appropriate output and added to the module through a simple hook:
      // site/ready.php wire()->addHookAfter('CachePlaceholders::getTokens', function (HookEvent $e) { $tokens = $e->return; $tokens['greeting'] = [ 'callback' => function (array $tokenData) { return ucfirst(wire('user')->name); } ]; $e->return = $tokens; }); Tokens can also include parameters that are parsed and passed to the callback function. There are more fully annotated examples and step-by-step instructions in the README on Github!
      Features
      A simple and fast token parser that calls the appropriate callback and runs automatically. Tokens may include multiple named or positional parameters, as well as multi-value parameters. A manual mode that allows you to replace tokens in custom pieces of cached content (useful if you're using the $cache API). Some built-in tokens for common use-cases: CSRF-Tokens, replacing values from superglobals and producing random hexadecimal strings. The token format is completely customizable, all delimiters can be changed to avoid collisions with existing tag parsers or template languages. Links
      Github Repository & documentation Module directory (pending approval) If you are interested in learning more, the README is very extensive, with more usage examples, code samples and usage instructions!
    • By Craig
      I've been using Fathom Analytics for a while now and on a growing number of sites, so thought it was about time there was a PW module for it.
      WayFathomAnalytics
      WayFathomAnalytics is a group of modules which will allow you to view your Fathom Analytics dashboard in the PW admin panel and (optionally) automatically add and configure the tracking code on front-end pages.
      Links
      GitHub Readme & documentation Download Zip Modules directory Module settings screenshot What is Fathom Analytics?
      Fathom Analytics is a simple, privacy-focused website analytics tool for bloggers and businesses.

      Stop scrolling through pages of reports and collecting gobs of personal data about your visitors, both of which you probably don't need. Fathom is a simple and private website analytics platform that lets you focus on what's important: your business.
      Privacy focused Fast-loading dashboards, all data is on a single screen Easy to get what you need, no training required Unlimited email reports Private or public dashboard sharing Cookie notices not required (it doesn't use cookies or collect personal data) Displays: top content, top referrers, top goals and more
    • By daniels
      This is a lightweight alternative to other newsletter & newsletter-subscription modules.
      You can find the Module in the Modules directory and on Github
      It can subscribe, update, unsubscribe & delete a user in a list in Mailchimp with MailChimp API 3.0. It does not provide any forms or validation, so you can feel free to use your own. To protect your users, it does not save any user data in logs or sends them to an admin.
      This module fits your needs if you...
      ...use Mailchimp as your newsletter / email-automation tool ...want to let users subscribe to your newsletter on your website ...want to use your own form, validation and messages (with or without the wire forms) ...don't want any personal user data saved in any way in your ProcessWire environment (cf. EU data regulation terms) ...like to subscribe, update, unsubscribe or delete users to/from different lists ...like the Mailchimp UI for creating / sending / reviewing email campaigns *I have only tested it with PHP 7.x so far, so use on owners risk
      EDIT:
      Since 0.0.4, instructions and changelog can be found in the README only. You can find it here  🙂
      If you have questions or like to contribute, just post a reply or create an issue or pr on github, thanks!
    • By MoritzLost
      Sorry for the convoluted title. I have a problem with Process modules that define a custom page using the page key through getModuleInfo (as demonstrated in this excellent tutorial by @bernhard). Those pages are created automatically when the module is installed. The problem is that the title of the page only gets set in the current language. That's not a problem if the current language (language of the superuser who is installing the module) is the default language; if it isn't, the Process page is missing a title in the default language. This has the very awkward effect that a user using the backend in the default language (or any other language) will see an empty entry in the setup menu:

      This screenshot comes from my Cache Control module which includes a Process page. Now I realize the description sounds obscure, but for us it's a common setup: We a multiple bilingual sites where the default language is German and the second language is English. While the clients use the CMS in German, as a developer I prefer the English interface, so whenever I install a Process module I get this problem.
      As a module author, is there a way to handle this situation? I guess it would be possible to use post-installation hooks or create the pages manually, but I very much prefer the declarative approach. The page title is already translatable (through the __ function), but of course at the time of installation there is no translation, and as far as I'm aware it's not possible to ship translations with a module so they are used automatically. Could this situation be handled better in the core? I would prefer if the module installation process would always set the title of the Process page in the default language, instead of the language of the current user.
×
×
  • Create New...