1

I am confused about the new Google Sheets API v4. My question is: how can I set validation rules for specified column(s) in spreadsheet? There is no useful tutorial with description how to use appropriate methods.

Result should look like following sample:

That validation should be set before data upload (which works fine).

My current code:

$client = getClient();
$service = new Google_Service_Sheets($client);
$fileId = 'my-document-id';

$body = new Google_Service_Sheets_SetDataValidationRequest(array(
    'setRange' => new Google_Service_Sheets_GridRange(
        array(
            'sheetId'=>'List1',
            'startColumnIndex'=>'0',
            'endColumnIndex'=>'1'
        )
    ),
    'setRule' => new Google_Service_Sheets_DataValidationRule(
        array(

            'setValues'=>array('YES','NO')
        )
    )
));


$sheetReq = new Google_Service_Sheets_Request($client);
$sheetReq->setSetDataValidation($body);


$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
    'requests' => $sheetReq
));


$result = $service->spreadsheets->batchUpdate($fileId, $batchUpdateRequest);
Jiří Valoušek
  • 611
  • 1
  • 7
  • 19

2 Answers2

3

Thank you @random-parts for help, it has brought me to the right track. If someone else will try to solve similar problem in PHP in feature, please find bellow fully working example:

    $client = $this->getClient();
    $service = new Google_Service_Sheets($client);
    $ary_values = ['yes','nope','maybe','never ever'];

    foreach( $ary_values AS $d ) {
        $cellData = new Google_Service_Sheets_ConditionValue();
        $cellData->setUserEnteredValue($d);
        $values[] = $cellData;
    }

    $conditions = new Google_Service_Sheets_BooleanCondition();
    $conditions->setType('ONE_OF_LIST');
    $conditions->setValues($values);

    $setRule= new Google_Service_Sheets_DataValidationRule();
    $setRule->setCondition($conditions);
    $setRule->setInputMessage('Please set correct value');
    $setRule->setShowCustomUi(true);

    $range = new Google_Service_Sheets_GridRange();
    $range->setStartRowIndex(1);
    $range->setEndRowIndex(5);
    $range->setStartColumnIndex(1);
    $range->setEndColumnIndex(2);
    $range->setSheetId(YOUR_SHEET_ID); //replace this by your sheet ID

    $valReq = new Google_Service_Sheets_SetDataValidationRequest();
    $valReq->setRule($setRule);
    $valReq->setRange($range);

    $sheetReq = new Google_Service_Sheets_Request();
    $sheetReq->setSetDataValidation($valReq);

    $bodyReq = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
    $bodyReq->setRequests($sheetReq);

    $result = $service->spreadsheets->batchUpdate($fileId, $bodyReq);
Jiří Valoušek
  • 611
  • 1
  • 7
  • 19
  • Can you explain what each of those classes do please? – fungusanthrax Feb 12 '18 at 15:40
  • 1
    * new Google_Service_Sheets_BooleanCondition(); - set validation for spreadsheet cell from values, which are collected to array above * new Google_Service_Sheets_DataValidationRule(); - set "hint" for cell which is visible before user click to array in your sheet * new Google_Service_Sheets_GridRange(); - set range for your new data validation (cols, rows) * new Google_Service_Sheets_SetDataValidationRequest(); - collect validation and range all together * new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(); - class for upload multiple changes to Google API just in one request – Jiří Valoušek Feb 12 '18 at 20:07
  • 1
    Please find more information about classes in Google API SDK and included samples https://developers.google.com/sheets/api/quickstart/php#step_3_set_up_the_sample – Jiří Valoušek Feb 12 '18 at 20:09
  • Do you know how to CLEAR the data validation after it has been set? – Alkarin Feb 21 '19 at 21:07
2

The DataValidationRule object would look like the following:

"rule": {
  "condition": {
    "type": "ONE_OF_LIST",
    "values": [
      { userEnteredValue: "Yes"},
      { userEnteredValue: "No"}
    ],
  },
  "inputMessage": "",
  "strict": true,
  "showCustomUi": true,
}

You want to use rule.condition.type ONE_OF_LIST and then enter the rule.condition.values you want in the list. showCustomUi will show the dropdown

A full example using google apps script from the Sheets script editor:

function setDataVal () {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];

  var validation = {
    "setDataValidation": {
      "range": {
        "sheetId": sheet.getSheetId(),
        "startRowIndex": 1,
        "endRowIndex": 5,
        "startColumnIndex": 1,
        "endColumnIndex": 5,
      },  
      "rule": {
        "condition": {
          "type": "ONE_OF_LIST",
          "values": [
            { userEnteredValue: "Yes"},
            { userEnteredValue: "No"}
          ],
        },
        "inputMessage": "",
        "strict": true,
        "showCustomUi": true,
      } 
    },
  }

  var req = {
    "requests": [validation],
    "includeSpreadsheetInResponse": false,
  }

  Sheets.Spreadsheets.batchUpdate(req, ss.getId())
}
  • Sheets API advanced service will have to be enabled
random-parts
  • 2,137
  • 2
  • 13
  • 20