Sheets API v4 - Creating a sheet with custom title, given a spreadsheet

Viewed 203

I've been trying to do this and it creates the sheet but not with the given sheet's title.

function addSheet($spreadsheet, $sheet_title) {
    $client = getClient();
    $service = new Google_Service_Sheets($client);
    
    $response = $service->spreadsheets->batchUpdate($spreadsheet->spreadsheetId, new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
        "requests" => [
            "addSheet" => new Google_Service_Sheets_AddSheetRequest([
                "properties" => new Google_Service_Sheets_SheetProperties([
                    "title" => $sheet_title
                ])
            ])
        ]
    ]));

    return $response;
}

What's wrong with it?

EDIT: I tried and it seems it's working with the following:

function addSheet($spreadsheet, $sheet_title) {
    $client = getClient();
    $service = new Google_Service_Sheets($client);

    $request_body = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
    $request_body->setRequests([
        "addSheet" => new Google_Service_Sheets_AddSheetRequest([
            "properties" => new Google_Service_Sheets_SheetProperties([
                "title" => $sheet_title
            ])
        ])
    ]);
    $response = $service->spreadsheets->batchUpdate($spreadsheet->spreadsheetId, $request_body);

    return $response;
}

But I still don't get what's wrong with the other one...

1 Answers

If you want to do it all in one line, you can do it as following:

$response = $service->spreadsheets->batchUpdate($spreadsheet->spreadsheetId, new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
        'requests' => array(
            'addSheet' => array(
                'properties' => array(
                    'title' => $sheet_title
                )
            )
        )
    )
  )
);

No need to create new objects within the Google_Service_Sheets_BatchUpdateSpreadsheetRequest.

Related