Getting server error when trying to use GridField to create relationship between DataObjects

StackOverflow https://stackoverflow.com/questions/22431880

  •  15-06-2023
  •  | 
  •  

Вопрос

I'm learning SilverStripe by creating a small website that lets the user manage their fragrances (i.e. perfumes/colognes). The user adds ingredients (that are used in the fragrances they have), then adds their fragrances, at which point they choose which ingredients are in the fragrance they're adding.

I've created the Ingredient and Fragrance classes which both extend DataObject. I've also created the IngredientsPage page which lets the user add/edit/delete ingredients (made up of a name and description) and lists all of the ingredients added so far, and this page is fully functional. I'm now trying to create the FragrancesPage page which will let the user add/edit/delete fragrances (made up of a name, description and ingredients) and list all the ones added so far, but I'm having some trouble.

The only way I know of to create the relationship between a Fragrance and Ingredients (one fragrance has many ingredients, and one ingredient belongs to many fragrances) is using a GridField (if there's a better way, let me know!), as this is what the SilverStripe tutorials get you to do (although in the tutorial it's for the CMS rather than the front-end). However, as soon as I try to add a GridField into the mix, I just get taken to an error page that says "Server Error: Sorry, there was a problem with handling your request.".

My code is as follows.

Ingredient.php:

<?php

class Ingredient extends DataObject {
    private static $db = array(
        'Name' => 'Text',
        'Description' => 'Text'
    );

    private static $belongs_many_many = array(
        'Fragrances' => 'Fragrance'
    );
}

?>

Fragrance.php:

<?php

class Fragrance extends DataObject {
    private static $db = array(
        'Name' => 'Text',
        'Description' => 'Text'
    );

    private static $many_many = array(
        'Ingredients' => 'Ingredient'
    );
}

?>

FragrancesPage.php:

<?php

class FragrancesPage extends Page {
    private static $icon = 'cms/images/treeicons/reports-file.png';
    private static $description = 'Fragrances page';
}

class FragrancesPage_Controller extends Page_Controller {
    private static $allowed_actions = array('FragranceAddForm');

    function FragranceAddForm() {
        $config = GridFieldConfig_RelationEditor::create();
        $config->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
            'Name' => 'Name',
            'Ingredient.Name' => 'Ingredient'
        ));

        $fragrances_field = new GridField(
            'Ingredients',
            'Ingredient',
            $this->Ingredients(),
            $config
        );

        $fields = new FieldList(
            new TextField('Name', 'Fragrance Name'),
            new TextareaField('Description', 'Fragrance Description'),
            $fragrances_field
        );

        $actions = new FieldList(
            new FormAction('doFragranceAdd', 'Add Fragrance')
        );

        $validator = new RequiredFields('Name', 'Description');

        return new Form($this, 'FragranceAddForm', $fields, $actions, $validator);
    }

    public function doFragranceAdd($data, $form) {
        $submission = new Fragrance();
        $form->saveInto($submission);
        $submission->write();

        return $this->redirectBack();
    }

    public function FragranceList() {
        $submissions = Fragrance::get()->sort('Name');

        return $submissions;
    }
}

?>

If I remove everything from FragrancesPage.php relating to the GridField, the page works fine. I just can't seem to get the GridField working, and don't know of any other way to create the relationship between Fragrances and Ingredients on the front-end. If the code for IngredientsPage.php will be helpful also, let me know and I'll add it.

Это было полезно?

Решение

my guess is that you have error reporting turned off, and that is why you only see such a meaning less error message.
you should turn on display_errors and error_reporting in your php.ini, .htaccess or _ss_environment.php (IMPORTANT: setting it in _config.php will NOT work, as it gets overwritten by the error handler)

the problem I see in your code is that trying to use $this->Ingredients() on FragrancesPage, but as far as I can see only the class Fragrances has a method Ingredients (method is 'magically' created for the many_many relation).
also, I think your setDisplayFields()

so basically you need to use $fragrance->Ingredients() instead of $this->Ingredients().
but that leads us to the next problem: you don't have a fragrance yet.
unfortunately, at this time, GridField only works if you already have an object. this means you have to split it into two forms or use an alternative.


Option 1: use CheckboxSetField to manage the many_many relation.

this will not allow creating Ingredients on the fly, it will only give you check boxes that you can tick to link the items.

public function FragranceAddForm() {
    $fragrances_field = new CheckboxSetField('Ingredients', 'Ingredient', Ingredient::get()->map());

    $fields = new FieldList(
        new TextField('Name', 'Fragrance Name'),
        new TextareaField('Description', 'Fragrance Description'),
        $fragrances_field
    );

    $actions = new FieldList(
        new FormAction('doFragranceAdd', 'Add Fragrance')
    );

    $validator = new RequiredFields('Name', 'Description');

    return new Form($this, __FUNCTION__, $fields, $actions, $validator);
}

public function doFragranceAdd($data, $form) {
    $submission = new Fragrance();
    $form->saveInto($submission);
    $submission->write();

    return $this->redirectBack();
}

Option 2: use GridField in a second form

this will allow creating Ingredients on the fly, but is a bit more work. and you might run into some troubles with GridField as it is not fully tested in the frontend yet.

(there is a recent question where I wrote a bit about GridField problems in frontends https://stackoverflow.com/a/22059197/1119263)
I guess this place is as good as any to finally write a tutorial/working example for frontend GridFields.
I took the liberty of refactoring your code a bit to include a edit functionality, its much nicer to have the GridField on the edit page than on a separate form.

As mentioned before, the GridField is not working that well in the frontend, there is a module to ease the pain, but it will still be rough around the edges and will require you to do some styling to make it look pretty. Find the module on Packagist or GitHub (you will need t

class Ingredient extends DataObject {
    private static $db = array(
        'Name' => 'Text',
        'Description' => 'Text'
    );

    private static $belongs_many_many = array(
        'Fragrances' => 'Fragrance'
    );

    public function getCMSFields() {
        // fields used by the GridField, don't let the CMSFields mislead you
        return new FieldList(
            TextField::create('Name', 'Name'),
            TextAreaField::create('Description', 'Description')
        );
    }
}

class Fragrance extends DataObject {
    private static $db = array(
        'Name' => 'Text',
        'Description' => 'Text'
    );

    private static $many_many = array(
        'Ingredients' => 'Ingredient'
    );
}

/**
 * Form in a separate class, so we can reuse it.
 * @param Controller $controller
 * @param string $name
 * @param Null|Fragrance $fragrance Either null to create a new one, or pass an existing to edit it and add Ingredients
 * @return Form
 */
class FragranceForm extends Form {
    public function __construct($controller, $name, $fragrance = null) {
        if ($fragrance && $fragrance->isInDB()) {
            // we can only use a GridField if the object exists and has already been saved

            // gridfield needs jQuery
            Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.min.js');
            // ensure we don't have 2 versions of jQuery
            Requirements::block(THIRDPARTY_DIR . '/jquery/jquery.js');
            $config = FrontEndGridFieldConfig_RelationEditor::create();
            $config->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
                'Name' => 'Name',
                'Description' => 'Description',
            ));
            $ingredientField = new FrontEndGridField(
                'Ingredients',
                'Ingredient',
                $fragrance->Ingredients(),
                $config
            );
        } else {
            $ingredientField = new LiteralField('Ingredients', '<p>Ingredients can be added after saving</p>');
        }
        $fields = new FieldList(
            new HiddenField('ID', ''),
            new TextField('Name', 'Fragrance Name'),
            new TextareaField('Description', 'Fragrance Description'),
            $ingredientField
        );

        $actions = new FieldList(
            new FormAction('doFragranceSave', 'Save Fragrance')
        );

        $validator = new RequiredFields('Name', 'Description');

        // populate the fields (ID, Name and Description) with the values from $fragrance. This does not effect the GridField
        if ($fragrance && $fragrance->exists()) {
            $fields->fieldByName('ID')->setValue($fragrance->ID);
            $fields->fieldByName('Name')->setValue($fragrance->Name);
            $fields->fieldByName('Description')->setValue($fragrance->Description);
            // there is actually a method for that, but we can't use it here,
            // because fields are not set yet. we could do it after __construct, but then we would
            // overwrite things set by the error handler, so lets just do it by hand
            // $this->loadDataFrom($fragrance);
        }
        parent::__construct($controller, $name, $fields, $actions, $validator);
    }

    public function doFragranceSave($data, $form) {
        if (isset($data['ID']) && $data['ID']) {
            $id = (int)$data['ID'];
            $fragrance = Fragrance::get()->byID($id);
        }
        if (!isset($fragrance) || !$fragrance || !$fragrance->exists()) {
            // if the ID was invalid or we don't have one, create a new Fragrance
            $fragrance = new Fragrance();
        }
        $form->saveInto($fragrance);
        $fragrance->write();

        // redirect to the edit page.
        $controller = $this->getController();
        $editLink = $controller->EditLink($fragrance->ID);
        return $controller->redirect($editLink);
    }
}

class FragrancesPage extends Page {

}

class FragrancesPage_Controller extends Page_Controller {
    private static $allowed_actions = array(
        'edit',
        'AddForm',
        'EditForm',
    );

    /**
     * the default action
     * @return ViewableData_Customised
     */
    public function index() {
        // $this->customise() lets you overwrite variables that you can use in the template later.
        return $this->customise(array(
            // set the AddForm to $Form instead of $AddForm, this way you can use $Form in template and can reuse the template
            'Form' => $this->AddForm(),
        ));
    }

    /**
     * edit action to edit an existing Fragrance
     * links will look like this /FragrancesPage/edit/$ID
     *
     * @param SS_HTTPRequest $request
     * @return SS_HTTPResponse|ViewableData_Customised
     */
    public function edit(SS_HTTPRequest $request) {
        $id = (int)$request->param('ID');
        $fragrance = Fragrance::get()->byID($id);
        if (!$fragrance || !$fragrance->exists()) {
            // fragrance not found? display a 404 error page
            return ErrorPage::response_for(404);
        }
        // now that we have a $fragrance, overwrite EditForm with a EditForm that contains the $fragrance
        $form = $this->EditForm($fragrance);
        $return = $this->customise(array(
            // also overwrite Title and Content, to display info about what the user can do here
            // if you don't overwrite that, it will display the Title and Content of the page
            'Title' => 'Edit: ' . $fragrance->Name,
            'Content' => '<p>you are editing an existing fragrance</p>',
            // set the Form to $Form instead of $EditForm, this way you can use $Form in template and can reuse the template
            'Form' => $form,
        ));
        // per default SilverStripe will try to use the following templates: FragrancesPage_edit.ss > FragrancesPage.ss > Page.ss
        // if you want to use a custom template here, you can specify that with ->renderWith()
        // but you probably won't need that anyway
        // $return = $return->renderWith(array('MyCustomTemplateName', 'Page'));
        return $return;
    }

    public function AddForm() {
        return new FragranceForm($this, __FUNCTION__);
    }

    public function EditForm($fragranceOrRequest = null) {
        // unfortunately, GridField / FormFields in general are a bit clumsy and do forget what item they where
        // suppose to edit, so we have to check what $fragranceOrRequest is and set/get the fragrance to/from session
        if ($fragranceOrRequest && is_a($fragranceOrRequest, 'Fragrance')) {
            $fragrance = $fragranceOrRequest;
            Session::set('FragrancesPage.CurrentFragrance', $fragrance->ID);
        } else {
            $fragrance = Fragrance::get()->byID(Session::get('FragrancesPage.CurrentFragrance'));
        }
        if (!$fragrance || !$fragrance->exists()) {
            // that's bad, some error has occurred, lets display an ugly 404 page
            return $this->httpError(404);
        }
        return new FragranceForm($this, __FUNCTION__, $fragrance);
    }

    public function EditLink($ID) {
        return $this->Link("edit/$ID");
    }
}

I know that's a lot to take in as someone still learning SilverStripe, if you have any questions, feel free to comment or just poke me on IRC

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top