4

I need to set a key=>value into the request that's pushed into Backpack's store method;

In v3 I had a working store method like so;

public function store(StoreRequest $request) {

    $request->request->set('account_type', User::ACCOUNT_TYPE_BASIC);
    $redirect_location = parent::storeCrud($request);
    return $redirect_location;

}

but in trying to stay current for a still in development project I'm updating to v4 and running into a problem with adding/removing anything to/from the $request object when trying to utilize the traitStore or traitUpdate methods that are recommended in the documentation.

This does NOT work;

public function store(StoreRequest $request) {

    $request->request->set('account_type', User::ACCOUNT_TYPE_BASIC);
    $redirect_location = $this->traitStore();
    return $redirect_location;

}

Specifically, the 'account_type' key is not included in the request that is sent to the database via traitStore, which uses only the fields defined in the (in this case) setupCreateOperation() method for this Crud.

Is there something I'm missing here or do I need to entirely manage the save/update on anything where I need to manipulate the request instead of utilizing the various backpack crud methods?

evanr
  • 4,396
  • 3
  • 20
  • 16

2 Answers2

3

The problem is likely that in v4. the getStrippedSaveRequest at the bttom of this class is intentionally dropping that attribute because it's not a registered field in the CRUD panel

  /**
     * Returns the request without anything that might have been maliciously inserted.
     * Only specific field names that have been introduced with addField() are kept in the request.
     */
    public function getStrippedSaveRequest()
    {
        return $this->request->only($this->getAllFieldNames());
    }

You can fix this by adding the this attribute as a hidden field in the CRUD panel like this:

$this->crud->addField([
    'name' => 'account_type',
    'type' => 'hidden'
]);

Now the field wont show up on the page but it will be registered and will no longer be removed before the create process.

Wesley Smith
  • 19,401
  • 22
  • 85
  • 133
  • This works for me in 2022, but I had to use `$this->crud->getRequest()->request->add` since crud->request is protected now. I also had to add my attribute name to `protected $fillable` in the model. – Benny G Oct 26 '22 at 10:55
0

store() doesn't take any parameters, so you need to add the attribute(s) to the crud->request directly.

Also, you can add the field on the fly, without creating as hidden in the form.

public function store()
    {

        $this->crud->request->request->add('account_type', User::ACCOUNT_TYPE_BASIC);
        $this->crud->addField(['type' => 'hidden', 'name' => 'account_type']);

        $response = $this->traitStore();

        return $response;

    }