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

Extending a baseform

Hey,

I'm trying to extend a baseform with all other form's. Extending the baseform does not execute the initialize function and add the required fields to the form. It works with parent::initialize(), but i was wondering if there's any option without having to call it in every form.

class BaseForm extends Form
{

    function initialize()
    {   
        $this->add(new Hidden($this->security->getTokenKey(), array('value' => $this->security->getToken())));
    }

}

Thanks, Timmeyy



39.4k
Accepted
answer

How about this:

use Phalcon\Forms\Form;

class BaseForm extends Form
{
    public function initialize()
    {
        $this->add(new Hidden($this->security->getTokenKey(), array('value' => $this->security->getToken())));
    }
}

and your normal forms:

class ContactForm extends BaseForm
{
    // No initialize = calls the parent initialize
}

or

class OtherForm extends BaseForm
{
    public function initialize()
    {
        parent::initialize();

        // Add more stuff here
    }
}


617

Well thats what I have now, so I guess there is no way around it :)

I don't think you can do it any other way really. The OtherForm::initialize() overrides the BaseForm::initialize() so you have to instruct your code to call the initialize model.