How to create a metafield with options list using GraphQL

sandeepks23
Shopify Partner
41 0 5

I tried to create a metafield manually in shopify admin and I have attached a screenshot of that. Can someone mention how to update the below given code so that I can achieve this requirement. My requirement is to create a location metafield that will have the options "Kochi" and "Trivandrum" and the user should be able to update its value only from these options.

Graphql mutation:

mutation CreateMetafieldDefinition($definition: MetafieldDefinitionInput!) {
  metafieldDefinitionCreate(definition: $definition) {
    createdDefinition {
      id
      name
      namespace
      key
      # add other return fields
    }
    userErrors {
      field
      message
      code
    }
  }
}


Variable:

{
  "definition": {
    "name": "Pizza size",
    "namespace": "bakery",
    "key": "pizza_size",
    "type": "dimension",
    "description": "The size (diameter) of the pizza in inches.",
    "validations": [
      {
        "name": "min",
        "value": "{\"unit\": \"INCHES\", \"value\": \"9\"}"
      },
      {
        "name": "max",
        "value": "{\"unit\": \"INCHES\", \"value\": \"15\"}"
      }
    ],
    "ownerType": "PRODUCT"
  }
}



Screenshot from 2023-05-24 13-15-53.pngScreenshot from 2023-05-24 13-17-50.png

 

 

Reply 1 (1)

sandeepks23
Shopify Partner
41 0 5

I have got an answer. For anyone looking for answer to similar requirement I am attaching the query and variables.

mutation = '''
    mutation CreateMetafieldDefinition($definition: MetafieldDefinitionInput!) {
      metafieldDefinitionCreate(definition: $definition) {
        createdDefinition {
          id
          name
          namespace
          key
        }
        userErrors {
          field
          message
          code
        }
      }
    }
'''

payload = {
    "query": mutation,
    "variables": {
        "definition": {
            "name": "Pizza size",
            "namespace": "bakery",
            "key": "pizza_size",
            "type": "list.single_line_text_field",
            "description": "The size (diameter) of the pizza in inches.",
            "validations": [
                {
                    "name": "choices",
                    "value": json.dumps(["Kochi", "Trivandrum"])
                }
            ],
            "ownerType": "PRODUCT"
        }
    }
}