We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Call Form class in Controller ?

How to call a Form class in a controller?

Ex: Have the following contact form:

    use Phalcon\Forms\Form,
        Phalcon\Forms\Element\Text,
        Phalcon\Forms\Element\Select;

    class ContactForm extends Form
    {
        public function initialize()
        {
            $this->add(new Text("name"));

            $this->add(new Text("telephone"));

            $this->add(new Select("telephoneType", TelephoneTypes::find(), array(
            'using' => array('id', 'name')
             )));
        }
    }

And call it in controller like this:

    class TestController extends \Phalcon\Mvc\Controller
    {

        public function indexAction()
        {

            $contact_form = new ContactForm();

        //$this->view->disable();
        }

    }

But it get error: Fatal error: Class 'ContactForm' not found in C:\xampp\htdocs\vngarena-phalcon\app\controllers\TestController.php on line 13

edited Mar '14

Check your Form namespace.

Humugus answer is correct.

I was stuggling with this aswell as i was mixin up the use of namespaces and using the default registerDirs(), and with the help of the above comment in combination with a Phalcon demo application i found two ways to make it work. You are calling it correct in the controller

If you are not using namespaces register the forms directory and add it to the loader, and don't use a namespace or you will get errors because of mixin it up like i did.


// in app/config/config.php add the formsDir
'application' => [
        'appDir'         => APP_PATH . '/',
        'controllersDir' => APP_PATH . '/controllers/',
        'modelsDir'      => APP_PATH . '/models/',
        'viewsDir'       => APP_PATH . '/views/',
        'pluginsDir'     => APP_PATH . '/plugins/',
        'formsDir'       => APP_PATH . '/forms/',
        'vendorDir'      => APP_PATH . '/vendor/',
        'cacheDir'       => BASE_PATH . '/cache/',
        'baseUri'        => '/phalcon-time/',
    ],

// in app/config/loader.php register the formsDir
$loader->registerDirs(
    [
        $config->application->controllersDir,
        $config->application->modelsDir,
        $config->application->formsDir
    ]
);

If you are using namespaces

// in app/config/loader.php use  registerNamespaces instead
$loader->registerNamespaces(
    [
        'PhalconTime\Forms'       => $config->application->formsDir,
        // etc
    ]
);

// in the form class use a namespace i.e.
namespace PhalconTime\Forms;