Jump to content
jrtderonde

Creating a new Page (with file upload)

Recommended Posts

Hi,

I'm working on a script that allows users to add a new Page to my installation of ProcessWire. I will explain how this script works below.

  • The user enters some information into a simple form
  • ^ This can include an image
  • The form is validated with jQuery
  • When valid, the form triggers a function through a class that handles the process

I will include some of the code below.

Form:

<form id="entry" class="entry" method="post" action="./" name="entry" enctype="multipart/form-data">
    <div class="row">
        <input type="text" name="fullName" id="fullName" placeholder="Naam initiatiefhouder *" data-validation="required" />
    </div>
    <div class="row">
        <input type="text" name="projectName" id="projectName" placeholder="Projectnaam *" data-validation="required" />
    </div>
    <div class="row">
        <input type="email" name="emailAddress" id="emailAddress" placeholder="E-mailadres *" data-validation="required" />
    </div>
    <div class="row">
        <textarea name="projectDescription" id="projectDescription" placeholder="Beschrijf uw initiatief *" data-validation="required"></textarea>
    </div>
    <div class="row">
        <input type="file" id="image" name="image" data-validation="mime size" data-validation-allowing="jpg, jpeg, png, gif" data-validation-max-size="2M" />
    </div>
    <div class="row">
        <input type="submit" name="submitEntry" id="submitEntry" value="Insturen" />
    </div>
</form>

So basically the "image" field is the field that allows the user to add a file (jpg, jpeg, png, gif - max 2mb).

Now, when all the information is valid it will post this form through the following function.

public function pushEntry ($input, $file) {

    // Unset the array
    $this->array = [];

    // If there is any data
    if ($input) {

        // Get some of the variables needed
        $this->name = $this->sanitizer->text($input->fullName);
        $this->email = $this->sanitizer->email($input->emailAddress);
        $this->project = $this->sanitizer->text($input->projectName);
        $this->description = $this->sanitizer->text($input->projectDescription);

        // Get the date
        $this->date = date("d-m-Y H:i:s");

        // Generate the title
        $this->title = "$this->project - $this->name";

        $this->duplicate = $this->pages->find("title=$this->title");

        // Generate the array
        $this->array = [
            "title" => $this->title,
            "fullName" => $this->name,
            "emailAddress" => $this->email,
            "projectName" => $this->project,
            "projectDescription" => $this->description,
            "date" => $this->date
        ];

        // Create the page
        $new = new Page();
        $new->template = $this->templates->get("entry"); 
        $new->parent = $this->pages->get("/entries/");

        foreach ($this->array as $key => $value) {

            // Foreach key and value, create a new page
            $new->$key = $value;

        }

        // Check if there is any duplicates
        if ($this->duplicate->count() == 0) {
            $new->save();
        } else {
            echo "Dit initiatief bestaat al.";
            exit;
        }

        // If there is an image
        if (!empty($file["image"]["name"])) {

            // Some variables
            $this->path = $this->config->paths->assets . "files/$new->id";

            // Set the extensions
            $this->extensions = [
                "jpg",
                "jpeg",
                "png",
                "gif"
            ];

            // Do the Wire
            $this->image = new WireUpload($file["image"]["name"]);
            $this->image->setMaxFiles(1);
            $this->image->setOverwrite(false);
            $this->image->setDestinationPath($this->path);
            $this->image->setValidExtensions($this->extensions);

            // Execute and check for errors
            $files = $this->image->execute();

            // Add the image to the page
            $this->fileName = $file["image"]["name"];
            $this->fullPath = $this->path ."/". $this->fileName;

            // Move the file
            $new->image->add($this->fullPath);

            // Unlink the file
            unlink($this->fullPath);

            // Save the page
            $new->save($new->id);

        }

    }

    // Return the array
    return $this->array;

}

The script adds a page to my installation of ProcessWire perfectly; except for the file upload. I encounter the following errors;

Warning: unlink(C:/wamp/www/gezondsteregio/site/assets/files/1135/dekkleden_header.1919x301.jpg): No such file or directory in C:\wamp\www\gezondsteregio\site\templates\controllers\home.php on line 106

Warning: filemtime(): stat failed for C:/wamp/www/gezondsteregio/site/assets/files/1135/dekkleden_header.1919x301.jpg in C:\wamp\www\gezondsteregio\wire\core\Pagefile.php on line 324

Warning: filemtime(): stat failed for C:/wamp/www/gezondsteregio/site/assets/files/1135/dekkleden_header.1919x301.jpg in C:\wamp\www\gezondsteregio\wire\core\Pagefile.php on line 324

I am really curious if someone can help me with this problem. I have tried this script on both my localhost (regular Apache) and my webhost (Fast CGI).

Regards,

Jim 


Oh, and I use the following script to trigger the function.

$entry = new Entry();

// If there is a post
if ($input->post->submitEntry && !empty($input->post->fullName) && !empty($input->post->emailAddress) && !empty($input->post->projectName) && !empty($input->post->projectDescription)):

    // Push the entry to the controller
    $entry->pushEntry($input->post, $_FILES);

endif;

Share this post


Link to post
Share on other sites

Hi @jrtderonde and welcome to the forums.

The first thing I notice is that you are uploading the file directly to the assets/files/page_id/ location. You should upload to a temp directory first, then $new->image->add('full_temp_path'), and then unlink from that temp location.

  • Like 2

Share this post


Link to post
Share on other sites

Hey Adrian, 

Thank you for your quick reply. It worked like a charm! I indeed tried to move the files directly from the user's end to a folder that corresponded to the page id. Knew I was wrong somewhere. Thanks!

  • Like 1

Share this post


Link to post
Share on other sites

Can I pass a remote file path to WireUpload to have it download it using curl?   Or do they need to always be local?

Share this post


Link to post
Share on other sites

Can I pass a remote file path to WireUpload to have it download it using curl?   Or do they need to always be local?

Maybe you are looking for WireHttp::download() ?

https://processwire.com/blog/posts/august-2014-core-updates-3/#new-download-capabilities-in-wirehttp-class

"...First it attempts to use cURL..."

Never used it though, just guessing. Sorry if ti is not the one you need.

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Spyros
      Hello
      I'm having a strange issue with the $page->find(), for some reason I'm missing some of the pages from the results. I found then that I was missing all the pages with the same "PAGE NAME". Is it a bug or am I missing something?
      PS 
      If I change the "PAGE NAME" of one of the missing ones then I'm retrieving the page without any problem.
      Thank you
    • By benbyf
      Hi, Looking to create form elements on a page–some input with a colection of form inputs and the appropriate labels and variables for that input. I've used ProForms in the past and rolled out my own when creating simply one off forms, but I wonder if anyone has found a good way of allowing form creation on page editing so that clients can adhocly make and edit forms?
      Thanks
    • By EyeDentify
      Hello Dear PW Gurus.

      Hope you fair well in these Corona Crisis times.

      Anyhow, i have a problem with a Cryptic error message that shows up when i am trying to Delete images out of a Images field.
      The Error message does say a little but it does not make sense to me why i can´t delete the images because of it.

      Is it some permission issue perhaps?

      I will attach screenshots of it and what i did prior to it.
      I am from sweden so ignore the funny words here and there.

      Hope you all can send me on the right track.
      i am running PW 3.0.139 on this install.

      Step1:

      Step 2: Select the images with the trashcan symbol

       
      Step 3: Cryptic Error message

      I am scratching my head on this one, have not seen this before.

      Thankfull for all help.
      /EyeDentify
    • By AndZyk
      Hello,
      I am currently building a intranet which will be hosted on the local network of a company. This intranet has many links to files on their fileserver with the protocol file://.
      So for example the links look like this file://domain.tld/filename.ext
      When I try to insert such a link into a URL field, I get the error, that only the protocol http:// is allowed. When I try to insert such a link into a CKEeditor link, it gets stripped out. Is it possible to insert such links into the FieldType URL and CKEditor.
      I know that I could use a FieldType Text or insert a RewriteRule in the .htaccess file, but I am looking for a more elegant solution. 😉
      Regards, Andreas
    • By neophron
      Hi,
      I was searching in the forum about a method how to remove a file extension, like .jpg, but couldn't find anything.
      There are some php methods out in the wild, but I wanted first to get sure, that Processwire is offering a solution.
      The background is, that a clients website has a lot of images, packed in different galleries. All image files contain the name, dimensions and other stuff about the image (painting). I want to echo the image name in the image tag.
       
      thanks 
×
×
  • Create New...