php-shopify icon indicating copy to clipboard operation
php-shopify copied to clipboard

GraphQL Variables Suggestion

Open wardwj opened this issue 4 years ago • 2 comments

Error: Notice: Undefined variable: input

$calculatedOrderId = $data['data']['orderEditBegin']['calculatedOrder']['id'];

$graphQL = <<<Query
mutation addVariantToOrder($input: OrderInput!){
  orderEditAddVariant(input: $input){
    calculatedOrder {
      id
      addedLineItems(first:5) {
        edges {
          node {
            id
            quantity
          }
        }
      }
    }
    userErrors {
      field
      message
    }
  }
}
Query;
        
$variables = [
  "input" => [
    "id" => $calculatedOrderId,
    "variantId" => "gid://shopify/ProductVariant/33346521235509",
    "quantity" => 1
  ]
];

$data = $shopify->GraphQL->post($graphQL, null, null, $variables);

Also having no joy with the example.

Could someone explain how the variables work when they are not in an array?

wardwj avatar Dec 16 '20 14:12 wardwj

Problem resolved, the variables in the query where being executed and was causing data to be added directly in to the query. Fix included escaping the variable by using \$ID. Would be a great reference to use in the readme for people who encounter the same problem.

$graphQL = <<<Query
mutation addVariantToOrder(\$id: ID!, \$variantId: ID!, \$quantity: Int!){
  orderEditAddVariant(id: \$id, variantId: \$variantId, quantity: \$quantity){
    calculatedOrder {
      id
      addedLineItems(first:5) {
        edges {
          node {
            id
            quantity
          }
        }
      }
    }
    userErrors {
      field
      message
    }
  }
}
Query;

$variables = [
  "id" => "gid://shopify/CalculatedOrder/3574530101",
  "variantId" => "gid://shopify/ProductVariant/33346521235509",
  "quantity" => 1
];

$data = $shopify->GraphQL->post($graphQL, null, null, $variables);

wardwj avatar Dec 16 '20 14:12 wardwj

I agree, this threw me off as well! A small notice in the GraphQL section would be great.

example: $ may need to be escaped when using heredoc syntax

$graphQL = <<<Query
    mutation (\$input: CustomerInput!) {
        customerCreate(input: \$input)
        {
            customer {
                id
                displayName
            }
            userErrors {
                field
                message
            }
        }
    }
Query;

NathanD19 avatar Apr 16 '21 01:04 NathanD19