MageWork

Back to home

Forms

<?php
    
/** @var Core_Model_Form $form */
$form = App::getSingleton('form', Core_Model::TYPE);

if ($form->isPost()) {
    $form->setFormFields( // Fields to retrieve on error
            [
                'firstname' => 'Firstname',
                'customer[firstname]' => 'Customer firstname',
                'customer[address][0]' => 'Customer address line 1',
                'email' => 'E-mail',
                'country' => 'Country',
            ]
        )
        ->setFormSpamField('subject') // Error if this (hidden) field is filled 
        ->setFormRequiredFields( // All required fields
            [
                'firstname',
                'customer[firstname]',
                'customer[address][0]',
            ]
        )
        ->setFormExceptedValues( // Field to check
            [
                'firstname' => '/[^0-9]/', // string = preg_match
                'email' => FILTER_VALIDATE_EMAIL, // int = filter_var
                'country' => ['fr', 'es', 'us'], // array = in_array
            ]
        )
        ->validate();

    if (!$form->getError()) {
        /* ... */
        $form->getFirstname(); // name="firstname"
        $form->getCustomerFirstname(); // name="customer[firstname]"
        $form->getData('customer_address_0'); // name="customer[address][0]"
        
        /** @var Core_Mail $message */
        $message = App::getSingleton('contact', Core_Mail::TYPE); // Magework_Mail_Contact
        
        $form->setMailSubject('New contact message!');
        $form->setMailMessage($message->render());
        $form->setMailSendTo('contact@example.com');
        $form->sendMail();
    } else {
        $form->getErrorFieldName();
        $form->getErrorFieldLabel();
    }
}