Chi February 2016

typo3 extbase: validate a form

I created a simple "subscribe to newsletter" form:

<f:form action="subscribe" method="post" name="newsletterform">
  <f:form.textfield id="name" name="name" required="true" />
  <f:form.textfield id="email" name="email" required="true"/>
  <button type="submit">Submit</button>
</f:form>

as you can see, this is not a form that's based on an existing model, I have no interest in saving newslettersubscriptions to the database (they'll be stored somewhere else anyways).

Now in my subscripeAction I want to do some form validating. I want to check if the email is really an email address, if its notEmpty etc. Is there a way to use the typo3 / extbase Validators? If so - how?

Answers


manish1706 February 2016

yes you can use fluid validator, but i would like to suggest you to use ValidationEngine

<input type="email" name="email" id="email" data-validation-engine="validate[required,custom[email]]"
data-errormessage-value-missing="Email is required!" 
data-errormessage-custom-error="Let me give you a hint: someone@nowhere.com" 
data-errormessage="This is the fall-back error message."/>


biesior February 2016

You can create dedicated class that is not a database model, but extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity and allows you to map the class by Extbase:

for an example file: typo3conf/ext/yourext/Classes/Domain/Form/SubscribeForm.php

<?php

namespace Vendor\Extname\Domain\Form;

use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;

class SubscribeForm extends AbstractEntity {

    /**
     * @var string
     * @validate NotEmpty
     */
    protected $name;

    /**
     * @var string
     * @validate NotEmpty
     * @validate EmailAddress
     */
    protected $email;

    /** @return string */
    public function getName() {
        return $this->name;
    }

    /** @param string $name */
    public function setName($name) {
        $this->name = $name;
    }

    /** @return string */
    public function getEmail() {
        return $this->email;
    }

    /** @param string $email */
    public function setEmail($email) {
        $this->email = $email;
    }

}

With such class you can work as with common domain model and it will not be saved to anything - https://docs.typo3.org/typo3cms/ExtbaseFluidBook/9-CrosscuttingConcerns/2-validating-domain-objects.html

in your controller you will just handle it with two actions:

/**
 * Displays the subscription form
 *
 * @param \Vendor\Extname\Domain\Form\SubscribeForm|NULL $subscribeForm
 * @dontvalidate $subscribeForm
 */
public function subscribeAction(\Vendor\Extname\Domain\Form\SubscribeForm $subscribeForm = NULL) {

}

/**
 * Handle the valid subscription form
 */
public function subscribeSaveAction(\Vendor\Extname\Domain\Form\SubscribeForm $subscribeForm) {
    // Handle the $subscribeForm
}

Post Status

Asked in February 2016
Viewed 3,030 times
Voted 7
Answered 2 times

Search




Leave an answer