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 6

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 teppo
      Needed a really simple solution to embed audio files within page content and couldn't find a module for that, so here we go. Textformatter Audio Embed works a bit like Textformatter Video Embed, converting this:
      <p>https://www.domain.tld/path/to/file.mp3</p> Into this:
      <audio controls class="TextformatterAudioEmbed"> <source src="https://www.domain.tld/path/to/file.mp3" type="audio/mpeg"> </audio> The audio element has pretty good browser support, so quite often this should be enough to get things rolling 🙂
      GitHub repository: https://github.com/teppokoivula/TextformatterAudioEmbed Modules directory: https://modules.processwire.com/modules/textformatter-audio-embed/
    • By Richard Jedlička
      Tense    
      Tense (Test ENvironment Setup & Execution) is a command-line tool to easily run tests agains multiple versions of ProcessWire CMF.
      Are you building a module, or a template and you need to make sure it works in all supported ProcessWire versions? Then Tense is exactly what you need. Write the tests in any testing framework, tell Tense which ProcessWire versions you are interested in and it will do the rest for you.

      See example or see usage in a real project.
      How to use?
      1. Install it: 
      composer global require uiii/tense 2. Create tense.yml config:
      tense init 3. Run it:
      tense run  
      For detailed instructions see Github page: https://github.com/uiii/tense
       
      This is made possible thanks to the great wireshell tool by @justb3a, @marcus and others.
       
      What do you think about it? Do you find it useful? Do you have some idea? Did you find some bug? Tell me you opinion. Write it here or in the issue tracker.
    • By Chris Bennett
      Hi all, I am going round and round in circles and would greatly appreciate if anyone can point me in the right direction.
      I am sure I am doing something dumb, or missing something I should know, but don't. Story of my life 😉

      Playing round with a module and my basic problem is I want to upload an image and also use InputfieldMarkup and other Inputfields.
      Going back and forth between trying an api generated page defining Fieldgroup, Template, Fields, Page and the InputfieldWrapper method.

      InputfieldWrapper method works great for all the markup stuff, but I just can't wrap my head around what I need to do to save the image to the database.
      Can generate a Field for it (thanks to the api investigations) but not sure what I need to do to link the Inputfield to that. Tried a lot of stuff from various threads, of varying dates without luck.
      Undoubtedly not helped by me not knowing enough.

      Defining Fieldgroup etc through the api seems nice and clean and works great for the images but I can't wrap my head around how/if I can add/append/hook the InputfieldWrapper/InputfieldMarkup stuff I'd like to include on that template as well. Not even sure if it should be where it is on ___install with the Fieldtype stuff or later on . Not getting Tracy errors, just nothing seems to happen.
      If anyone has any ideas or can point me in the right direction, that would be great because at the moment I am stumbling round in the dark.
       
      public function ___install() { parent::___install(); $page = $this->pages->get('name='.self::PAGE_NAME); if (!$page->id) { // Create fieldgroup, template, fields and page // Create new fieldgroup $fmFieldgroup = new Fieldgroup(); $fmFieldgroup->name = MODULE_NAME.'-fieldgroup'; $fmFieldgroup->add($this->fields->get('title')); // needed title field $fmFieldgroup->save(); // Create new template using the fieldgroup $fmTemplate = new Template(); $fmTemplate->name = MODULE_NAME; $fmTemplate->fieldgroup = $fmFieldgroup; $fmTemplate->noSettings = 1; $fmTemplate->noChildren = 1; $fmTemplate->allowNewPages = 0; $fmTemplate->tabContent = MODULE_NAME; $fmTemplate->noChangeTemplate = 1; $fmTemplate->setIcon(ICON); $fmTemplate->save(); // Favicon source $fmField = new Field(); $fmField->type = $this->modules->get("FieldtypeImage"); $fmField->name = 'fmFavicon'; $fmField->label = 'Favicon'; $fmField->focusMode = 'off'; $fmField->gridMode = 'grid'; $fmField->extensions = 'svg png'; $fmField->columnWidth = 50; $fmField->collapsed = Inputfield::collapsedNever; $fmField->setIcon(ICON); $fmField->addTag(MODULE_NAME); $fmField->save(); $fmFieldgroup->add($fmField); // Favicon Silhouette source $fmField = new Field(); $fmField->type = $this->modules->get("FieldtypeImage"); $fmField->name = 'fmFaviconSilhouette'; $fmField->label = 'SVG Silhouette'; $fmField->notes = 'When creating a silhouette/mask svg version for Safari Pinned Tabs and Windows Tiles, we recommend setting your viewbox for 0 0 16 16, as this is what Apple requires. In many cases, the easiest way to do this in something like illustrator is a sacrificial rectangle with no fill, and no stroke at 16 x 16. This forces the desired viewbox and can then be discarded easily using something as simple as notepad. Easy is good, especially when you get the result you want without a lot of hassle.'; $fmField->focusMode = 'off'; $fmField->extensions = 'svg'; $fmField->columnWidth = 50; $fmField->collapsed = Inputfield::collapsedNever; $fmField->setIcon(ICON); $fmField->addTag(MODULE_NAME); $fmField->save(); $fmFieldgroup->add($fmField); // Create: Open Settings Tab $tabOpener = new Field(); $tabOpener->type = new FieldtypeFieldsetTabOpen(); $tabOpener->name = 'fmTab1'; $tabOpener->label = "Favicon Settings"; $tabOpener->collapsed = Inputfield::collapsedNever; $tabOpener->addTag(MODULE_NAME); $tabOpener->save(); // Create: Close Settings Tab $tabCloser = new Field(); $tabCloser->type = new FieldtypeFieldsetClose; $tabCloser->name = 'fmTab1' . FieldtypeFieldsetTabOpen::fieldsetCloseIdentifier; $tabCloser->label = "Close open tab"; $tabCloser->addTag(MODULE_NAME); $tabCloser->save(); // Create: Opens wrapper for Favicon Folder Name $filesOpener = new Field(); $filesOpener->type = new FieldtypeFieldsetOpen(); $filesOpener->name = 'fmOpenFolderName'; $filesOpener->label = 'Wrap Folder Name'; $filesOpener->class = 'inline'; $filesOpener->collapsed = Inputfield::collapsedNever; $filesOpener->addTag(MODULE_NAME); $filesOpener->save(); // Create: Close wrapper for Favicon Folder Name $filesCloser = new Field(); $filesCloser->type = new FieldtypeFieldsetClose(); $filesCloser->name = 'fmOpenFolderName' . FieldtypeFieldsetOpen::fieldsetCloseIdentifier; $filesCloser->label = "Close open fieldset"; $filesCloser->addTag(MODULE_NAME); $filesCloser->save(); // Create Favicon Folder Name $fmField = new Field(); $fmField->type = $this->modules->get("FieldtypeText"); $fmField->name = 'folderName'; $fmField->label = 'Favicon Folder:'; $fmField->description = $this->config->urls->files; $fmField->placeholder = 'Destination Folder for your generated favicons, webmanifest and browserconfig'; $fmField->columnWidth = 100; $fmField->collapsed = Inputfield::collapsedNever; $fmField->setIcon('folder'); $fmField->addTag(MODULE_NAME); $fmField->save(); $fmFieldgroup->add($tabOpener); $fmFieldgroup->add($filesOpener); $fmFieldgroup->add($fmField); $fmFieldgroup->add($filesCloser); $fmFieldgroup->add($tabCloser); $fmFieldgroup->save(); /////////////////////////////////////////////////////////////// // Experimental Markup Tests $wrapperFaviconMagic = new InputfieldWrapper(); $wrapperFaviconMagic->attr('id','faviconMagicWrapper'); $wrapperFaviconMagic->attr('title',$this->_('Favicon Magic')); // field show info what $field = $this->modules->get('InputfieldMarkup'); $field->name = 'use'; $field->label = __('How do I use it?'); $field->collapsed = Inputfield::collapsedNever; $field->icon('info'); $field->attr('value', 'Does this even begin to vaguely work?'); $field->columnWidth = 50; $wrapperFaviconMagic->add($field); $fmTemplate->fields->add($wrapperFaviconMagic); $fmTemplate->fields->save(); ///////////////////////////////////////////////////////////// // Create page $page = $this->wire( new Page() ); $page->template = MODULE_NAME; $page->parent = $this->wire('pages')->get('/'); $page->addStatus(Page::statusHidden); $page->title = 'Favicons'; $page->name = self::PAGE_NAME; $page->process = $this; $page->save(); } }  
    • By Sebi
      Since it's featured in ProcessWire Weekly #310, now is the time to make it official:
      Here is Twack!
      I really like the following introduction from ProcessWire Weekly, so I hope it is ok if I use it here, too. Look at the project's README for more details!
      Twack is a new — or rather newish — third party module for ProcessWire that provides support for reusable components in an Angular-inspired way. Twack is implemented as an installable module, and a collection of helper and base classes. Key concepts introduced by this module are:
      Components, which have separate views and controllers. Views are simple PHP files that handle the output for the component, whereas controllers extend the TwackComponent base class and provide additional data handling capabilities. Services, which are singletons that provide a shared service where components can request data. The README for Twack uses a NewsService, which returns data related to news items, as an example of a service. Twack components are designed for reusability and encapsulating a set of features for easy maintainability, can handle hierarchical or recursive use (child components), and are simple to integrate with an existing site — even when said site wasn't originally developed with Twack.
      A very basic Twack component view could look something like this:
      <?php namespace ProcessWire; ?> <h1>Hello World!</h1> And here's how you could render it via the API:
      <?php namespace Processwire; $twack = $modules->get('Twack'); $hello = $twack->getNewComponent('HelloWorld'); ?> <html> <head> <title>Hello World</title> </head> <body> <?= $hello->render() ?> </body> </html> Now, just to add a bit more context, here's a simple component controller:
      <?php namespace ProcessWire; class HelloWorld extends TwackComponent { public function __construct($args) { parent::__construct($args); $this->title = 'Hello World!'; if(isset($args['title'])) { $this->title = $args['title']; } } } As you can see, there's not a whole lot new stuff to learn here if you'd like to give Twack a try in one of your projects. The Twack README provides a really informative and easy to follow introduction to all the key concepts (as well as some additional examples) so be sure to check that out before getting started. 
      Twack is in development for several years and I use it for every new project I build. Also integrated is an easy to handle workflow to make outputs as JSON, so it can be used to build responses for a REST-api as well. I will work that out in one section in the readme as well. 
      If you want to see the module in an actual project, I have published the code of www.musical-fabrik.de in a repository. It runs completely with Twack and has an app-endpoint with ajax-output as well.
      I really look forward to hear, what you think of Twack🥳!
      Features Installation Usage Quickstart: Creating a component Naming conventions & component variants Component Parameters directory page parameters viewname Asset handling Services Named components Global components Ajax-Output Configuration Versioning License Changelog
    • By Robin S
      Page Reference Default Value
      Most ProcessWire core inputfield types that can be used with a Page Reference field support a "Default value" setting. This module extends support for default values to the following core inputfield types:
      Page List Select Page List Select Multiple Page Autocomplete (single and multiple) Seeing as these inputfield types only support the selection of pages a Page List Select / Page List Select Multiple is used for defining the default value instead of the Text / Textarea field used by the core for other inputfield types. This makes defining a default value a bit more user-friendly.
      Note that as per the core "Default value" setting, the Page Reference field must be set to "required" in order for the default value to be used.
      Screenshot

       
      https://github.com/Toutouwai/PageReferenceDefaultValue
      https://modules.processwire.com/modules/page-reference-default-value/
×
×
  • Create New...