GithubHelp home page GithubHelp logo

craftcms / guest-entries Goto Github PK

View Code? Open in Web Editor NEW
106.0 12.0 26.0 338 KB

Accept anonymous entry submissions with Craft.

License: MIT License

PHP 78.28% HTML 21.72%
craft-plugin craftcms craft2 craft3

guest-entries's Introduction

Guest Entries for Craft CMS

Allow guests to create entries from your site’s front end.

Requirements

Guest Entries requires Craft CMS 4.0.0+ or 5.0.0+.

Installation

You can install Guest Entries from the Plugin Store or with Composer.

From the Plugin Store

Go to the Plugin Store in your project’s control panel (in an environment that allows admin changes), search for “Guest Entries,” then click Install.

With Composer

Open your terminal and run the following commands:

# Navigate to your project directory:
cd /path/to/my-project

# Require the plugin package with Composer:
composer require craftcms/guest-entries -w

# Install the plugin with Craft:
php craft plugin/install guest-entries

Settings

From the plugin settings page, you can configure…

  • …which sections should allow guest entry submissions;
  • …the default entry authors and statuses;
  • …and whether submissions should be validated before being accepted.

Usage

A basic guest entry template should look something like this:

{# Macro to help output errors: #}
{% macro errorList(errors) %}
    {% if errors %}
        {{ ul(errors, { class: 'errors' }) }}
    {% endif %}
{% endmacro %}

{# Default value for the `entry` variable: #}
{% set entry = entry ?? null %}

<form method="post" action="" accept-charset="UTF-8">
    {# Hidden inputs required for the form to work: #}
    {{ csrfInput() }}
    {{ actionInput('guest-entries/save') }}

    {# Custom redirect URI: #}
    {{ redirectInput('success') }}

    {# Section for new entries: #}
    {{ hiddenInput('sectionHandle', 'mySectionHandle') }}

    {# Entry properties and custom fields: #}
    <label for="title">Title</label>
    {{ input('text', 'title', entry ? entry.title, { id: 'title' }) }}
    {{ entry ? _self.errorList(entry.getErrors('title')) }}

    <label for="body">Body</label>
    {{ tag('textarea', {
        text: entry ? entry.body,
        id: 'body',
        name: 'fields[body]',
    }) }}
    {{ entry ? _self.errorList(entry.getErrors('body')) }}

    {# ... #}

    <button type="submit">Publish</button>
</form>

Note
The process of submitting data and handling success and error states is outlined in the controller actions documentation.

Supported Params

The following parameters can be sent with a submission:

Name Notes Required
sectionHandle Determines what section the entry will be created in.
sectionUid Can be sent in lieu of sectionHandle.
sectionId Can be sent in lieu of sectionHandle.
typeId Entry type ID to use. This may affect which custom fields are required. When absent, the first configured type for the specified section is used.
title Optional if the section has automatic title formatting enabled.
slug Explicitly sets the new entry’s slug.
postDate Value should be processable by DateTimeHelper::toDateTime()
expiryDate Value should be processable by DateTimeHelper::toDateTime()
parentId Nest this entry under another. Invalid for channels and structures with a maximum depth of 1.
siteId Create the entry in a specific site.
enabledForSite Whether the entry should be enabled in this site. The global enabled setting is configurable by administrators, so this alone will not immediately publish something.
fields[...] Any custom fields you want guests to be able to populate.

Form Tips

Specifying a Section + Entry Type

The plugin determines what section the new entry is created in by looking for a sectionHandle, sectionUid, or sectionId param, in this order. Entry types, on the other hand, can only be defined by a typeId param—but because IDs can be unstable between environments, you must look them up by a known identifier.

Granted you will already have a section (or at least a section handle), the easiest way to do this is via the section model:

{% set targetSection = craft.app.sections.getSectionByHandle('resources') %}
{% set entryTypes = targetSection.getEntryTypes() %}

{# Select a single type, identified by its handle: #}
{% set targetEntryType = collect(entryTypes).firstWhere('handle', 'document') %}

{{ hiddenInput('sectionId', targetSection.id) }}
{{ hiddenInput('typeId', targetEntryType.id) }}

Sending Custom Fields

Custom field data should be nested under the fields key, with the field name in [squareBrackets]:

<input
    type="text"
    name="fields[myCustomFieldHandle]"
    value="{{ entry ? entry.myCustomFieldHandle }}">

If entries in the designated section are enabled by default, validation will occur on all custom fields, meaning those marked as required in the entry type’s field layout must be sent with the submission. Refer to the field types documentation to learn about the kinds of values that Craft accepts.

Warning
Omitting a field from your form does not mean it is safe from tampering! Clever users may be able to modify the request payload and submit additional field data. If this presents a problem for your site, consider using an event to clear values or reject submissions.

Validation Errors

If there are validation errors on the entry, the page will be reloaded with the populated craft\elements\Entry object available under an entry variable. You can access the posted values from that object as though it were a normal entry—or display errors with getErrors(), getFirstError(), or getFirstErrors().

Note
The entry variable can be renamed with the “Entry Variable Name” setting in the control panel. This might be necessary if you want to use a form on an entry page that already injects a variable of that name.

Redirection

Send a redirect param to send the user to a specific location upon successfully saving an entry. In the example above, this is handled via the redirectInput('...') function. The path is evaluated as an object template, and can include properties of the saved entry in {curlyBraces}.

Submitting via Ajax

If you submit your form via Ajax with an Accept: application/json header, a JSON response will be returned with the following keys:

  • success (boolean) – Whether the entry was saved successfully
  • errors (object) – All of the validation errors indexed by field name (if not saved)
  • id (string) – the entry’s ID (if saved)
  • title (string) – the entry’s title (if saved)
  • authorUsername (string) – the entry’s author’s username (if saved)
  • dateCreated (string) – the entry’s creation date in ISO 8601 format (if saved)
  • dateUpdated (string) – the entry’s update date in ISO 8601 format (if saved)
  • postDate (string, null) – the entry’s post date in ISO 8601 format (if saved and enabled)
  • url (string, null) – the entry’s public URL (if saved, enabled, and in a section that has URLs)

Viewing Entries

Using a redirect param allows you to show a user some or all of the content they just submitted—even if the entry is disabled, by default.

Warning
Take great care when displaying untrusted content on your site, especially when subverting moderation processes!

Enabled by Default

Entries in sections with URLs can be viewed immediately, with this redirect param:

{{ redirectInput('{url}') }}

Disabled by Default

In order to display an entry that is disabled, you will need to set up a custom route

<?php

return [
    // This route uses the special `{uid}` token, which will
    // match any UUIDv4 generated by Craft:
    'submissions/confirmation/<entryUid:{uid}>' => ['template' => '_submissions/confirmation'],
];

…and direct users to it by including {{ redirectInput('submissions/confirmation/{uid}') }} in the entry form. Your template (_submissions/confirmation.twig) will be responsible for looking up the disabled entry and displaying it, based on the entryUid route token that Craft makes available:

{% set preview = craft.entries()
    .status('disabled')
    .section('documents')
    .uid(entryUid)
    .one() %}

{# Bail if it doesn’t exist: #}
{% if not preview %}
    {% exit 404 %}
{% endif %}

{# Supposing the user’s name was recorded in the `title` field: #}
<h1>Thanks, {{ preview.title }}!</h1>

<p>Your submission has been recorded, and is awaiting moderation.</p>

This query selects only disabled entries so that the “preview” is invalidated once the entry goes live. This “confirmation” URI does not need to match the actual URI of the entry.

Events

Guest Entries augments the normal events emitted during the entry lifecycle with a few of its own, allowing developers to customize the submission process.

The following snippets should be added to your plugin or module’s init() method, per the official event usage instructions.

The beforeSaveEntry event

Plugins can be notified before a guest entry is saved, using the beforeSaveEntry event. This is also an opportunity to flag the submission as spam, and prevent it being saved:

use craft\helpers\StringHelper;
use craft\guestentries\controllers\SaveController;
use craft\guestentries\events\SaveEvent;
use yii\base\Event;

// ...

Event::on(
    SaveController::class,
    SaveController::EVENT_BEFORE_SAVE_ENTRY,
    function(SaveEvent $e) {
        // Get a reference to the entry object:
        $entry = $e->entry;

        // Perform spam detection logic of your own design:
        if (StringHelper::contains($entry->title, 'synergy', false)) {
            // Set the event property:
            $e->isSpam = true;
        }
    }
);

The afterSaveEntry event

Plugins can be notified after a guest entry is saved, using the afterSaveEntry event:

use craft\guestentries\controllers\SaveController;
use craft\guestentries\events\SaveEvent;
use yii\base\Event;

// ...

Event::on(
    SaveController::class,
    SaveController::EVENT_AFTER_SAVE_ENTRY,
    function(SaveEvent $e) {
        // Grab the entry
        $entry = $e->entry;

        // Was it flagged as spam?
        $isSpam = $e->isSpam;
    }
);

The afterError event

Plugins can be notified right after a submission is determined to be invalid using the afterError event:

use craft\guestentries\controllers\SaveController;
use craft\guestentries\events\SaveEvent;
use yii\base\Event;

// ...

Event::on(
    SaveController::class,
    SaveController::EVENT_AFTER_ERROR,
    function(SaveEvent $e) {
        // Grab the entry
        $entry = $e->entry;

        // Get any validation errors
        $errors = $entry->getErrors();
    }
);

guest-entries's People

Contributors

andris-sevcenko avatar angrybrad avatar augustmiller avatar bencroker avatar benjamindavid avatar brandonkelly avatar furioursus avatar i-just avatar iainhenderson avatar kylebakerrockit avatar makeilalundy avatar olivierbon avatar roberskine avatar sammcqueen avatar selvinortiz avatar stenvdb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

guest-entries's Issues

Ajax 500 error

I'm getting a 500 server error when submitting the guest entries form via Ajax. The entries are saving in Craft regardless of the error, but I'm not getting a response back. This is using v1.5.2.

screen shot 2016-11-23 at 11 04 41 am

<script src="/jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $("#form").submit(function(ev) {
                    ev.preventDefault();
                    var data = $(this).serialize();

                    $.ajax({
                        method: 'POST',
                        url: "/",
                        data: data,
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                    })
                    .success(function(data) {
                        console.log('success', data);
                    })
                    .error(function(data){
                        console.log('error', data);
                    });
                });
            });
        </script>
        <form id="form" method="post" action="" accept-charset="UTF-8">
            {{ getCsrfInput() }}
            <input type="hidden" name="action" value="guestEntries/saveEntry">
            <input type="hidden" name="redirect" value="/">
            <input type="hidden" name="sectionId" value="3">

            <label for="title">Title</label>
            <input id="title" type="text" name="title">

            <label for="title">Body</label>
            <input id="title" type="text" name="fields[body]">

    <input type="submit" value="Publish">
</form>

When I reverted back to v1.5.1, the guest entries works as expected.

onBeforeSave not Triggering

Hey Brad,
I don't think we can raise an event within the context of a controller, at least not one that a plugin.init() will be able to register for, though I could be wrong.

During testing, I found that onBeforeSave was not triggering (using your example which seems accurate) so I went ahead and added a service and using $this within the context of a service actually worked.

So I basically moved the onBeforeSave method in GuestEntriesController into the new GuestEntriesService which I created and then replaced the call to that method from the controller which was $this->onBeforeSave to craft()->guestEntries->onBeforeSave

Let me know if this makes sense or maybe I need to drink some more coffee: )

Guest Entry submission doesn't seem to trigger a cache invalidation?

My observation has been that submitting an anonymous entry using this plugin does not trigger a cache invalidation. So when the page reloads, the user's content is not visible yet. However, if I reload a CP URL, that seems to trigger the cache invalidation.

My workaround was to use the Cache Clear plugin, but it's kind of a blunt instrument, I'd rather have the appropriate cache keys cleared when the user submits their entry data.

If this can't be added to the roadmap, it might be worth pointing out in the readme?

Thanks!

Clarify validation (entry model vs content model)

The README states:

If there is a validation error on the entry, then the page will be reloaded with an entry variable available to it

However, (at least in v1), actually only the element's content is validated, not the entry model itself. I was adding errors to the entry thinking it would stop submission, but since it only validates the content, it doesn't.

v1 example of adding captcha validation:

public function guestEntriesBeforeSaveHandler(GuestEntriesEvent $event)
{
    $entry = $event->params['entry'];
    $verified = craft()->custom_helper->verifyCaptcha();

    if (!$verified) {
        $element->addError('recaptcha', 'There was a problem with the captcha.');

        // We also need this, because only $element->content is validated, not $element.
        $event->isValid = false;
    }
}

Is the same true in v2? If so maybe just a note in the README clarifying that only the content is validated, not the entire entry.

Variables available after submit

Are there any variables available after submit that I can use in a URL parameter? I'm trying to attach a guest entry to a commerce order and having that entry ID available in the URL would allow me to attach it to a custom field on checkout -- atleast that's the idea. Any advice would be appreciated.

Thanks.

Populating Tables/Matrix Fields

Is there a way to populate a Matrix Field or a Table using the GuestEntries plugin?

Not sure what the name field should be set to if it's already possible.

Error after 99 entries

I'm receiving 500 (Internal Server Errors) after 99 entries. Is there any way to bypass this limit?

Validation error with file input type

I have a guest entries front-end form which allows users to upload photos. Certain fields, including the file input are required, but when the page reloads after returning a validation error all page elements including and after file select aren't rendered. If I add an image to the file select input prior to triggering a validation error that field is rendered but then it has JS set in the value, breaking all the markup on the page from that point.

This is my first time using the plugin so I'm positive it's something I didn't setup or code correctly. Here's the form code as it is now:

<form action="" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
  {{ getCsrfInput() }}
  {{ craft.sproutInvisibleCaptcha.protect() }}
  <input name="MAX_FILE_SIZE" type="hidden" value="67108864">
  <input type="hidden" name="action" value="guestEntries/saveEntry">
  <input type="hidden" name="redirect" value="/thankyou">
  <input type="hidden" name="sectionId" value="13">
  <input type="hidden" name="typeId" value="13">
  <input type="hidden" name="title" value="Photo Gallery">
  <input type="hidden" name="postDate[date]" value="{{ "now"|date("m/d/Y") }}">
  <input type="hidden" name="postDate[time]" value="{{ "now"|date("h:i:s A") }}">

  {% if guestEntry is defined %}{% if guestEntry.errors|length > 0 %}
    <div class="alert alert-danger">
      <h3>There was a problem with your submission:</h3>
      {% for error in guestEntry.errors %}
      {% for errormessage in error %}
      <p>{{errormessage}}</p>
      {% endfor %}
      {% endfor %}
    </div>
  {% endif %}{% endif %}

  <input required type="text"{% if guestEntry is defined %} value="{{ guestEntry.userFirstName }}"{% endif %} class="form-control" name="fields[userFirstName]" id="input_first_name" placeholder="First Name">
  <input required type="text"{% if guestEntry is defined %} value="{{ guestEntry.userLastName }}"{% endif %} class="form-control" name="fields[userLastName]" id="input_last_name" placeholder="Last Name">
  <input type="text"{% if guestEntry is defined %} value="{{ guestEntry.userTitle }}"{% endif %} class="form-control" name="fields[userTitle]" id="input_title" placeholder="Title">
  <input required type="file"{% if guestEntry is defined %} value="{{ guestEntry.userPhoto }}"{% endif %} class="form-control" name="fields[userPhoto]" id="input_photo" accept="image/*">
  <textarea required name="fields[userQuote]" rows="8" cols="40" placeholder="Add your quote" class="form-control" id="input_quote">{% if guestEntry is defined %}{{ guestEntry.userQuote }}{% endif %}</textarea>
  <input type="text"{% if guestEntry is defined %} value="{{ guestEntry.userFacebookHandle }}"{% endif %} class="form-control" name="fields[userFacebookHandle]" id="input_facebook_handle" placeholder="Add your Facebook handle">
  <input type="text"{% if guestEntry is defined %} value="{{ guestEntry.userInstagramHandle }}"{% endif %} class="form-control" name="fields[userInstagramHandle]" id="input_instagram_handle" placeholder="Add your Instagram handle">
  <input type="text"{% if guestEntry is defined %} value="{{ guestEntry.userTwitterHandle }}"{% endif %} class="form-control" name="fields[userTwitterHandle]" id="input_twitter_handle" placeholder="Add your Twitter handle">

  <button type="submit" class="btn btn-lg btn-primary">Send Request</button>
</form>

Error submitting entries over HTTP after upgrading to Craft 3.3.14

Hi, sorry if this isn't the right place to create this issue.

After upgrading from Craft from 3.3.7 to 3.3.14, this plugin stopped behaving as expected when saving an entry over ajax (with CSRF protection disabled).

At the new version, I get a 400 response with this body:

{
    "error": "Unable to verify your data submission."
}

In case it helps, this is in the logs and seems relevant:

2019-11-05 10:44:32 [-][-][-][error][yii\web\HttpException:400] yii\web\BadRequestHttpException: Unable to verify your data submission. in /app/vendor/yiisoft/yii2/web/Controller.php:166
Stack trace:
#0 /app/vendor/craftcms/cms/src/web/Controller.php(143): yii\web\Controller->beforeAction(Object(yii\base\InlineAction))
#1 /app/vendor/craftcms/cms/src/controllers/TemplatesController.php(72): craft\web\Controller->beforeAction(Object(yii\base\InlineAction))
#2 /app/vendor/yiisoft/yii2/base/Controller.php(155): craft\controllers\TemplatesController->beforeAction(Object(yii\base\InlineAction))
#3 /app/vendor/craftcms/cms/src/web/Controller.php(187): yii\base\Controller->runAction('render', Array)
#4 /app/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('render', Array)
#5 /app/vendor/craftcms/cms/src/web/Application.php(299): yii\base\Module->runAction('templates/rende...', Array)
#6 /app/vendor/yiisoft/yii2/web/Application.php(103): craft\web\Application->runAction('templates/rende...', Array)
#7 /app/vendor/craftcms/cms/src/web/Application.php(284): yii\web\Application->handleRequest(Object(craft\web\Request))
#8 /app/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#9 /app/web/index.php(21): yii\base\Application->run()
#10 {main}

I'm able to downgrade Craft back to 3.3.7 to keep things from breaking, but that's obviously not going to be a long term solution.

Empty values passed for relationship field result in SQLSTATE[23000]: Integrity constraint violation

I posted this to SE as there was already an issue, but I'm posting here as well, as it seems like it could be a bug, in either Guest Entries or Craft itself.

When an entries field (or presumably any relation field) is submitted as an array with an empty string, this error is thrown.

This would be common if you had a <select> with a "Choose One…" label and no value.

The same behavior can be triggered by passing a null or [''] value to an entries field via setContentFromPost:

$entry->setContentFromPost([
  'product' => null
]);

or

$entry->setContentFromPost([
  'product' => ['']
]);

So, to work around this, in guestEntries.beforeSave, I'm making sure it isn't null or [0 => '']:

$entry = $event->params['entry'];

// Seemingly, when the `fields.product` post data has an array
// with an empty string (like it does from an unselected <select>),
// we get a CDbException SQLSTATE[23000]: Integrity constraint violation error.
// The same thing seems to happen when setContentFromPost receives null on a
// relation field, so we'll coalesce to empty string.
$product = array_filter(craft()->request->getPost('fields.product'));
$entry->setContentFromPost([
  'product' => $product ?? '',
]);

changes to syntax after C3 RC15

Worth noting that after upgrading to RC15 the syntax changed in how to reference errors - it should now be something like this, prefixing the field handle with "field:"

submission.getErrors('field:' ~ field.handle)

Save Entry Event

It would be nice to have a guestEntries.saveEntry event to be able to do post processing on the entry once it has been saved to the db.

Redirect not working on Craft 3 RC4

I've copied the code that is in the readme file and the redirect hidden input is not working. It just goes to the home page or root directory of the site. The entries are saving correctly. The only thing that isn't working is the redirect.

My code is something like this:

<form method="post" action="" accept-charset="UTF-8">
    {{ csrfInput() }}
    <input type="hidden" name="action" value="guest-entries/save">
    <input type="hidden" name="redirect" value="transactions">
    <input type="hidden" name="sectionId" value="3">

    <label for="memo">Memo</label>
    <input type="text" name="fields[memo]" />

    <label for="amount">Amount</label>
    <input type="number" name="fields[amount]" step="0.01" />

    <input type="submit" value="Save">
</form>

I even tried removing the empty action="" from the form tag or setting it to where I wanted it to redirect. Still doesn't work. I'm guessing it might be because I'm using Craft 3 RC4 and this might be fixed in the future.

Any suggestions?

Default author assignment only showing "Admin"

I've set up a user with permissions to create and edit entries in the section I want guest entries to post to, but all I can select from the dropdown is Admin.

Is there a setting I've missed?

`Validate?` is set to off, but still receiving validation error when submitting via axios

Hi there! I am submitting a Guest Entry form via axios, and am receiving the following error "Values did not pass validation.". Validate? is set to off in the plugin settings, as I'm doing my own validation via Javascript.

const inputs = selectAll(wrapper, 'input, textarea')
    validateInputs(inputs, () => {
      // Guest Entries plugin is expecting data in FormData format, not json
      const formdata = new FormData();
      inputs.forEach((element) => {
        formdata.append(element.name, element.value);
      });

      axios.post(handler, formdata)
        .then((res) => {
          console.log(res);
          // Show message no matter what, as reviews have to be approved by mods anyway
          showMessage(true)
        })
        .catch(err => console.error(err))
    })
  })

I even tried via axios with a JSON object for the data, and I get the same validation error.

validateInputs(inputs, () => {
      // Guest Entries plugin is expecting data in FormData format, not json
      // const formdata = new FormData();
      // inputs.forEach((element) => {
      //   formdata.append(element.name, element.value);
      // });

      let obj = inputs.reduce((acc, current) => {
        acc[current.name] = current.value
        return acc
      }, {})

      axios({
        method: 'post',
        url: handler,
        data: obj,
        config: { headers: {'Accept': 'application/json' }}
      })
        .then((res) => {
          console.log(res);
          // Show message no matter what, as reviews have to be approved by mods anyway
          showMessage(true)
        })
        .catch(err => console.error(err))
    })

Create a disabled entry

On default a created entry will be enabled. This can also be set with a input field:

<input type="hidden" class="field" name="enabled" value="1">

But it's not possible to create a disabled entry. Values "" or "0" won't change a thing.

"Validate Entry" lightswitch in plugin settings remains true always

Hi I think there might be a small bug within the plugin settings area:

  1. Go to Guest Entries plugin settings
  2. Set the "Validate Entry" setting for a section to false (lightswitch off)
  3. Press save
  4. Re-visit the entries plugin settings to find that light switch is on again i.e. "Validate Entry" setting did not save to false.

Thanks!

How to set postDate in submission

Hi,

I have guest entries being submitted but disabled by dfault (so they can be checked before being published)

However, the post Date appears to be blank.

How can I set the date in the form to the date is the date/time as of the submission?

Latest 1.5.2 Release doesn't return entry URL in AJAX Submissions

Though it's been committed to the v1 branch, and it's mentioned in the readme (I know, the readme on GitHub isn't the readme for the release):

url (string) - live URL of the entry saved if it has a URL

The latest release doesn't return URLs.

Looks like @brandonkelly was close to releasing 1.5.3 with this new bit, but it never made it.

Anyway, downloading the latest on branch works

Image Exception -- can't save assets from front-end entry form

I'm using Craft 3.2 RC1 with Guest Entries 2.2.3. I have a guest entry form set up and works just fine unless I try to upload an image. My abbreviated form looks like this:

<form method="post" action="" enctype="multipart/form-data" accept-charset="UTF-8">
    {{ csrfInput() }}

    <input type="hidden" name="action" value="guest-entries/save">
    <input type="hidden" name="sectionUid" value="25e26550-2b9f-418a-84cc-4e08ca46913a">

    <label for="title">Title</label>
    <input id="title" type="text" name="title"/>

    <label for="thumbnailImage">Thumbnail Image</label>
    <input type="file" id="thumbnailImage" name="fields[thumbnailImage]" value="Upload">

    <input type="submit" value="Submit">
</form>

When I try to upload an image, I get an Image Exception error:

Image Exception – craft\errors\ImageException
The file “assets5d239a84ae0f09.86917575.jpg” does not appear to be an image.

Ae file with that name is written to the temp directory, but is empty (zero bytes).

The odd thing is that the correct and working image file is also copied to the asset directory, but not visible from the Assets panel in Craft.

Any thoughts?

Allow customised authorUsername in the form

Current behaviour:

I believe the plugin cant does not change authorUsername in the front-end.

e.g

<input type="hidden" name="authorUsername" :value="[email protected]" />

and authorUsername is defined in plugin in settings.

Desire behaviour:

the guest-entries/save action can take below value

<input type="hidden" name="authorId" :value="userId" />

Is there anyway to customize the 'action' route(s) ?

I work on a sign-up process on a project that will need to create two entry (for 2 different sections) on the same "form" (I will handle this by ajax) and I want to avoid the use of guest-entries/save in my template to be more constant with my form process. Is there any way to use the builtin Craft routing to do that ?

Already try with something like this :

return [
    'app' => [
        'app/create/parent' => 'guest-entries/save',
        'app/create/child' => 'guest-entries/save',
    ],
];

...and that’s not working event if the official doc on the advanced routing let you believe that you can add a custom routing for a controller.

POST param “sectionId” doesn’t exist.

Not sure what Im doing wrong here. Using the default form from the docs..
Set my sectionId, but im getting this error once i submit.
POST param “sectionId” doesn’t exist.

Any help would be appreciated.
Thanks

Craft CMS 2.6.2964

Settings Not Saving

Hello,

When going to the settings of Guest Entries and saving new settings, the changes are not being saved. The page redirects to the admin/settings page and says the plugin settings are saved. However, when returning to the Guest Entries settings, they are reverted back to the previous state. In order to work around the issue, I had to revert PHP to 7.1 and Guest entries to 2.2.1. Please let me know if you have any questions.

Craft 3.1.8
Guest Entries 2.2.2
PHP 7.2.8
MySQL 5.7.23

Thanks,

Todd Kersey

Save Draft

It would be great if we could save entries as a draft instead of publishing immediatly.

Entry not visible in entries list in CP

Hi

When I use this plugin, I don't see the entry in the control panel under the "entries" tab (entries > all entries). The strange this is: it is in the database, it also shows up on the dashboard (in the recent content widget), and if I click it there, I can edit it. It's just missing from the entries page.

Validate custom fields issue

Hi @brandonkelly ,

in the SaveController there's a reference to validateCustomFields which was removed by Beta30. This makes plugin stop working. Is there a possibility of a news version? From what I'm seeing it's only in the SaveController, but you know this better than I do.

Thanks!
Jakub

Default author assignment setting doesn't work with large user sets

I have a guest entries section where thousands of existing users have author privileges, so they all show up in the dropdown…but only the first 100 of them, so I can never select the default user I want.

Thinking this selection should probably be an elementselect modal instead.

example not working with craft cms 3

Hi there,

getting crazy! :-)

I have a field "body", but there is nothing stored! Title is working

field

grafik

section

grafik

code snippet

<label for="body">Body</label>
<textarea id="body" name="fields[body]">
    {%- if entry is defined %}{{ entry.body }}{% endif -%}
</textarea>

what I'm doing wrong!?

thanks!

Required element fields do not pass validation when they should

In my form I have fields like:

      <input type="hidden" name="fields[materials][]" value="5416">
  • materials is a entries field, marked required in the entry type.
  • I have "Validate?" enabled for this section
  • On submission I get the error "Materials cannot be blank."
  • If I un-require the field, the submission works, and the materials field data is populated from the submission as it should be.
  • Required validation on other fields (text) seems to work as expected.
  • I thought maybe it had to do with the default author not having appropriate permissions, so I tried them as admin and it still didn't work

Craft CMS 3.0.12, Guest Entries 2.1.3

Upgrade from v2.1.3 to v2.2 causes Undefined index: sectionUid error

I have a site (running Craft 3.1.5) that already uses v2.1.3 with a form successfully submitting guest entries. After upgrading the site is brought down by an Undefined index error.

Here is a screenshot of the error:
http://share.jmx2.com/wPyM8X

Here is the Stack trace from my error log:

2019-01-29 15:02:56 [-][-][b9vv10blf81c1iohffioliqj66][error][yii\base\ErrorException:8] yii\base\ErrorException: Undefined index: sectionUid in /Users/john/Sites/mysite/vendor/craftcms/guest-entries/src/models/Settings.php:72
Stack trace:
#0 /Users/john/Sites/mysite/vendor/yiisoft/yii2/base/Component.php(180): craft\guestentries\models\Settings->setSections()
#1 /Users/john/Sites/mysite/vendor/yiisoft/yii2/base/Model.php(732): craft\guestentries\models\Settings->__set()
#2 /Users/john/Sites/mysite/vendor/craftcms/cms/src/base/Plugin.php(213): craft\guestentries\models\Settings->setAttributes()
#3 /Users/john/Sites/mysite/vendor/yiisoft/yii2/base/Component.php(180): craft\guestentries\Plugin->setSettings()
#4 /Users/john/Sites/mysite/vendor/yiisoft/yii2/BaseYii.php(546): craft\guestentries\Plugin->__set()
#5 /Users/john/Sites/mysite/vendor/yiisoft/yii2/base/BaseObject.php(107): yii\BaseYii::configure()
#6 /Users/john/Sites/mysite/vendor/yiisoft/yii2/base/Module.php(158): craft\guestentries\Plugin->__construct()
#7 /Users/john/Sites/mysite/vendor/craftcms/cms/src/base/Plugin.php(127): craft\guestentries\Plugin->__construct()
#8 /Users/john/Sites/mysite/vendor/yiisoft/yii2/di/Container.php(383): craft\guestentries\Plugin->__construct()
#9 /Users/john/Sites/mysite/vendor/yiisoft/yii2/di/Container.php(383): ReflectionClass->newInstanceArgs()
#10 /Users/john/Sites/mysite/vendor/yiisoft/yii2/di/Container.php(156): yii\di\Container->build()
#11 /Users/john/Sites/mysite/vendor/yiisoft/yii2/BaseYii.php(349): yii\di\Container->get()
#12 /Users/john/Sites/mysite/vendor/craftcms/cms/src/services/Plugins.php(890): yii\BaseYii::createObject()
#13 /Users/john/Sites/mysite/vendor/craftcms/cms/src/services/Plugins.php(223): craft\services\Plugins->createPlugin()
#14 /Users/john/Sites/mysite/vendor/craftcms/cms/src/base/ApplicationTrait.php(1208): craft\services\Plugins->loadPlugins()
#15 /Users/john/Sites/mysite/vendor/craftcms/cms/src/web/Application.php(112): craft\web\Application->_postInit()
#16 /Users/john/Sites/mysite/vendor/yiisoft/yii2/base/BaseObject.php(109): craft\web\Application->init()
#17 /Users/john/Sites/mysite/vendor/yiisoft/yii2/base/Application.php(206): craft\web\Application->__construct()
#18 /Users/john/Sites/mysite/vendor/craftcms/cms/src/web/Application.php(100): craft\web\Application->__construct()
#19 /Users/john/Sites/mysite/vendor/yiisoft/yii2/di/Container.php(383): craft\web\Application->__construct()
#20 /Users/john/Sites/mysite/vendor/yiisoft/yii2/di/Container.php(383): ReflectionClass->newInstanceArgs()
#21 /Users/john/Sites/mysite/vendor/yiisoft/yii2/di/Container.php(156): yii\di\Container->build()
#22 /Users/john/Sites/mysite/vendor/yiisoft/yii2/BaseYii.php(349): yii\di\Container->get()
#23 /Users/john/Sites/mysite/vendor/craftcms/cms/bootstrap/bootstrap.php(255): yii\BaseYii::createObject()
#24 /Users/john/Sites/mysite/vendor/craftcms/cms/bootstrap/web.php(42): ::unknown()
#25 /Users/john/Sites/mysite/web/index.php(20): ::unknown()
#26 /Users/john/.composer/vendor/laravel/valet/server.php(151): ::unknown()
#27 {main}

Managing errors

Am using GuestEntries in an add-on to permit site visitors to add a 'comment' to an existing entry.
The error I am experiencing is if an error is returned - eg if a required field is not filled - the returned template is treating the submitted Guest entry/comment and not the Source entry that is being commented against as an entry object.

This changes the title and contents of the page being requested/shown.

Any thoughts on how to resolve this issue appreciated (aside from front-loading my error validation to the client-side)

Can't save images

I have a form that is supposed to save images (assets):

        <label for="images">Add images</label>
        <input type="file" id="images" name="fields[images][]" multiple><br>
        {% if entry is defined %}
            {{ errorList(entry.getErrors('mailing')) }}
        {% endif %}

Here's the fields:
image

When I choose a file and submit, nothing is in images for that entry.

What am I doing wrong?

project.yaml sections are wacky (__assoc__)

Never seen this, assuming it isn't right…

    enabled: '1'
    licenseKey: null
    schemaVersion: 2.1.0
    settings:
      enableCsrfProtection: '1'
      entryVariable: guestEntry
      sections:
        __assoc__:
          -
            - 11b69b4a-1092-43ff-bcdd-eb21216363cb
            -
              allowGuestSubmissions: '1'
              authorUid: a2f92020-7412-4bbb-b86f-6635555ae888
              enabledByDefault: '1'
              runValidation: '1'
              sectionUid: 11b69b4a-1092-43ff-bcdd-eb21216363cb
          -
            - 231b3d4f-4f58-47d8-9dec-a490e49917c1
            -
              allowGuestSubmissions: '1'
              authorUid: a2f92020-7412-4bbb-b86f-6635555ae888
              enabledByDefault: '1'
              runValidation: '1'
              sectionUid: 231b3d4f-4f58-47d8-9dec-a490e49917c1
          -
            - 9fef0e0f-6b9d-401e-95c7-0e7487a590db
            -
              allowGuestSubmissions: '1'
              authorUid: a2f92020-7412-4bbb-b86f-6635555ae888
              enabledByDefault: ''
              runValidation: '1'
              sectionUid: 9fef0e0f-6b9d-401e-95c7-0e7487a590db
          -
            - abd44075-dff1-4f3f-8b87-63a6857f3d0d
            -
              allowGuestSubmissions: '1'
              authorUid: a2f92020-7412-4bbb-b86f-6635555ae888
              enabledByDefault: ''
              runValidation: '1'
              sectionUid: abd44075-dff1-4f3f-8b87-63a6857f3d0d

Incorrect documenation for guestentries.php?

The documentation says I can override the "Guest Entries’ config settings" by creating a new guestentries.php file in my craft/config/ folder.

I have done this, and the file contains:

<?php

return array(
    'entryVariable' => 'commentEntry',
);

No change, the entry variable does not change.

If I instead edit craft/plugins/guestentries/config.php to look like this:

<?php

return array(
    /**
     * The name of the variable that submitted entries should be assigned to when the template is reloaded
     * in the event of a validation error.
     */
    'entryVariable' => 'commentEntry',
);

everything works fine.

Is the documentation just out of date and I'm actually meant to edit craft/plugins/guestentries/config.php or is there a bug with reading the config from guestentries.php?

Response contains too much information about approved author

When posting via AJAX, the response returned by the plugin contains sensitive data. The default author's email, id, full name, etc. along with their hashed password.

Example response below.

{  
  "success":true,
  "title":"title",
  "cpEditUrl":"http:\/\/localhost:8080\/index.php?p=admin\/entries\/section\/1-title",
  "author":{  
    "id":"1",
    "enabled":"1",
    "archived":"0",
    "locale":"en_gb",
    "localeEnabled":true,
    "slug":null,
    "uri":null,
    "dateCreated":{  
      "date":"2016-06-04 07:36:42.000000",
      "timezone_type":1,
      "timezone":"+00:00"
    },
    "dateUpdated":{  
      "date":"2016-06-04 07:36:42.000000",
      "timezone_type":1,
      "timezone":"+00:00"
    },
    "root":null,
    "lft":null,
    "rgt":null,
    "level":null,
    "searchScore":null,
    "username":"admin",
    "photo":null,
    "firstName":null,
    "lastName":null,
    "email":"[email protected]",
    "password":"$2y$13$8E3p.uMuv4X8dcHJa.I\/CuFxaYHeBKuu6H1ijgpCMj.9MjDTYf1gG",
    "preferredLocale":null,
    "weekStartDay":"0",
    "admin":"1",
    "client":"0",
    "locked":"0",
    "suspended":"0",
    "pending":"0",
    "lastLoginDate":{  
      "date":"2016-06-04 14:09:53.000000",
      "timezone_type":1,
      "timezone":"+00:00"
    },
    "invalidLoginCount":null,
    "lastInvalidLoginDate":null,
    "lockoutDate":null,
    "passwordResetRequired":"0",
    "lastPasswordChangeDate":{  
      "date":"2016-06-04 07:36:42.000000",
      "timezone_type":1,
      "timezone":"+00:00"
    },
    "unverifiedEmail":null,
    "newPassword":null,
    "currentPassword":null,
    "verificationCodeIssuedDate":null
  },
  "postDate":"04\/06\/2016"
}

Handle 100k plus users

We are running into an issue where the cp is having to handle 100k+ users being populated into a the author options dropdown. It's on sections that we don't need to enable guest entries for, but do need to allow the createEntries permission for the users group.

Not sure what the best way to handle:

  • Could there be a setting to only show users which have permission to access the cp?
  • Or an event to allow us to modify the authors query so we can tweak that?
  • Or only load the author list when guest entries are enabled for a specific section?

Thanks,
Sam

Validation Error: Author Id cannot be blank

I'm getting an author id validation error whenever I try to submit.
Console is showing this:

[info][craft\services\Elements::saveElement] Element not saved due to validation error: Array
(
    [authorId] => Array
        (
            [0] => Author Id cannot be blank.
        )
)

I only have one user and have set this as the default author in the Guest Entries plugin settings.
All other validations seem to be working correctly. Disabling validations in the settings does allow new entries. I've tried disabling CSRF protection with no joy.

Also tried adding a hidden authorId form input set to 1 just to test, but still receive the cannot be blank error.

Craft: 3.1.7

Saving multiple categories and image

Hi,

Can anyone help, how would I go about saving categories in Craft from a form with checkboxes.

Also, how would I go about saving an image via input type="file"

Thanks

Misleading plugin settings if section’s selected author gets deleted

If a user gets deleted who was previously selected as the default author within the Guest Entries plugin settings, when you revisit the plugin settings, the section will continue to be enabled, and it will look like a default author is selected – but it won’t be the (now deleted) previously-selected user. And it won’t be clear that there is an issue.

Submitting via Ajax from same server / another domain [need help]

Hey there,

I'm trying to add entries from my "api" to the Craft-CMS-3 system. But the ajax call isn't working.

request
	.post({
		url: 'http://staging.cms.xxxxx.com',
		headers: {
			'Accept': 'application/json',
			'content-type': 'application/json'
		}
	})
	.form({
		action: 'guest-entries/save',
		sectionId: 11,
		title: req.body.title
	})
	.on('response', function (response: any) {
		res.end(JSON.stringify(response));
	});

but there isn't any entry in my cms and the response isn't a json

{
	"statusCode": 302,
	"headers": {
		"server": "nginx",
		"date": "Tue, 01 Aug 2017 19:08:23 GMT",
		"content-type": "text/html; charset=iso-8859-1",
		"content-length": "291",
		"connection": "close",
		"location": "https://staging.cms.xxxxx.com/"
	},
	"request": {
		"uri": {
			"protocol": "http:",
			"slashes": true,
			"auth": null,
			"host": "staging.cms.xxxxx.com",
			"port": 80,
			"hostname": "staging.cms.xxxxx.com",
			"hash": null,
			"search": null,
			"query": null,
			"pathname": "/",
			"path": "/",
			"href": "http://staging.cms.xxxxx.com/"
		},
		"method": "POST",
		"headers": {
			"Accept": "application/json",
			"content-type": "application/x-www-form-urlencoded",
			"content-length": 73
		}
	}
}

fyi: I can't change the header "content-type"

thx!!

Greetings crazyx13th

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.