0

Dear Silverstripe 4 users, i need someone to explain me how to slove my problem. Am building ecommerce module, i create data object for insert new proucts and categories without any problems.

Probelm start when i try to create related products for new product. I do that from has_many relatian and ListboxField and that is work good but i dont want to do that with list box filed. I want to create new tab like (Root.RelatedProducts) and there to have gridfield where i can add existing product.

I know to create grid with headers, actions and other grid configuration. When i create grid i only can add new product.

How to implement to chose existing product and show in grid in specific tab?

class Product extends Page {

private static $has_many = [
    'RelatedProducts' => Product::class
];

public function getCMSFields()
{
    $fields = parent::getCMSFields();

  $gridFieldConfig = GridFieldConfig_RecordEditor::create();


    $gridFieldConfig = GridFieldConfig::create()->addComponents(
        new GridFieldToolbarHeader(),
        new GridFieldAddNewButton('toolbar-header-right'),
        new GridFieldSortableHeader(),
        new GridFieldDataColumns(),
        new GridFieldPaginator(10),
        new GridFieldEditButton(),
        new GridFieldDeleteAction(),
        new GridFieldDetailForm()
    );
    $gridField = new GridField("RelatedProducts", "Related products", $products,  $gridFieldConfig);

}

}

Ivan
  • 5,139
  • 11
  • 53
  • 86

1 Answers1

0

If you want to add existing products to the relation, you can use another gridfield config. Silverstripe has some predefined configs available and you took the Gridfield_RecordEditor.

If you use Gridfield_RelationEditor you also get a component to search for existing records. From the docblock of RelationEditor:

Similar to {@link GridFieldConfig_RecordEditor}, but adds features to work on has-many or many-many relationships.

Allows to search for existing records to add to the relationship, detach listed records from the relationship (rather than removing them from the database), and automatically add newly created records to it.

You can configure it more like this:

 GridFieldConfig_RelationEditor::create()
    ->getComponentByType('GridFieldAddExistingAutocompleter')
    ->setSearchFields('MyField');

By the way: I'd use a many_many relation, as a product could be related to more than one product.

wmk
  • 4,598
  • 1
  • 20
  • 37