GiarcTNA
GiarcTNA

Reputation: 499

Silverstripe - Include controller within controller

I have a customer controller that has a form on it. What I want to do is add a form from another controller to the same customer page. Is there a way to do this in Silverstripe bar using an iFrame?

Upvotes: 0

Views: 239

Answers (1)

Zauberfisch
Zauberfisch

Reputation: 4015

well, yes, but you probably need some modifications to your code.

there are 2 main approaches I can think of to accomplish your goal:

1. separate the form creation from the controller action:

class Foo extends Controller {
    private static $allowed_actions = ['FooForm', 'BarForm'];

    public function FooForm() {
        return new Form($this, __FUNCTION, new FieldList(), new FieldList());
    }

    public function BarForm() {
        return Bar::get_bar_form($this, __FUNCTION__);
    }
}

class Bar extends Controller {
    private static $allowed_actions = ['BarForm'];

    public function BarForm() {
        return static::get_bar_form($this, __FUNCTION__);
    }

    /**
     * A static function that accepts the controller (Bar or Foo in this case) and a name
     * This way, this form can easily be used on other controllers as well
     * Just be aware that this way, the Forms controller is not always the same, so if you have a custom form that calls specific methods of the Bar controller this will not work
     */
    public static function get_bar_form($controller, $name) {
        return new Form($controller, $name, new FieldList(), new FieldList());
    }
}

2. nested controllers:

SilverStripe allows you to nest controllers. This is essentially what Forms are already doing. A SilverStripe Form is a Controller (or rather RequestHandler).
In SilverStripe, any Controller action can return another RequestHandler (Controller is a subclass of RequestHandler) which will then be processed.

So you could return the whole Bar controller from within the Foo Controller and have it run as a child controller. So the URL might be /foo/bar/BarForm.
But with standard Controllers, I think you will need to do some tinkering to have nested URLs.

Take a look at my ContentBlock/PageBuilder module for an advanced example of nested controllers with Forms:
PageBuilder_Field.php#L179
PageBuilder_Field_Handler_Block.php#L32

Upvotes: 1

Related Questions