Allow guests to create pages from Panel or frontend

Here’s some example code you can use in the controller of the frontend form page:

<?php 

return function($site, $pages, $page) {
  $error = null;
  if(r::method() === 'POST') {
    // The form has been sent
    
    // Build an array of the data you want to allow as fields
    // get() fetches the form field value with that `name`
    $data = array(
      'title' => get('title'),
      'text' => get('text')
    );
    
    // Validate the data
    if($whatever) $error = 'Something is invalid.';
    
    // Create a new page as child of the current page
    // You can also use a different page by using `page('whatever')->children()->create()`
    $p = $page->children()->create(uniqid(), 'yourtemplate', $data);
    
    // Upload an image
    try {
      // This uses the form field with `name="file"`
      // See http://php.net/manual/en/features.file-upload.post-method.php#example-392 on how to structure your form
      $upload = new Upload($p->root() . DS . '{safeFilename}');
    } catch(Error $e) {
      switch($e->getCode()) {
        case Upload::ERROR_MISSING_FILE:
          // File does not exist
          $error = 'No file uploaded.';
          break;
        // See the Upload class for other error values
      }
    }
  }
  
  return compact('error');
};
1 Like