1

I have tried several solution posted in this forum and others as well but it has not helped so far. So I am posting my question finally. BTW, I am using CakePHP 3.6.

I am trying to pass a variable ($product->id) via submit button in view.ctp to my controller action "addit" but I just get "Undefined variable: id " (I have tried addit($id) and addit() either of case I have the same result.)

view.ctp

<p>
    <?php echo $this->Form->create('NULL',['url'=>['controller'=>'products','action'=>'addit']]);?>
    <?php echo $this->Form->input('id', ['type' => 'hidden', 'value' => $product->id]); ?>

    <?php echo $this->Form->button('Add to cart now');?>

    <?php echo $this->Form->end();?>

</p>

Controller:Products

public function addit() {
    $this->autoRender = false;
    if ($this->request->is('post')) {
        // $this->Products->addProduct($this->request->data['Cart']['product_id']);
        echo "".$this->Products->get($id);//for test
    } else {
        echo "".$this->Products->get($id);//for test
    }
 }
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
vins
  • 449
  • 4
  • 13
  • 2
    You are sending your data using post method but trying to receive in controller using get method !! in controller use $this->request->data($id); for post request. – Alimon Karim Sep 29 '18 at 18:21
  • thanks for your response :)... i later realised it ...and got it fixed :) – vins Oct 01 '18 at 10:12

2 Answers2

1

According to Cakephp 3.6

All POST data can be accessed using Cake\Http\ServerRequest::getData(). Any form data that contains a data prefix will have that data prefix removed. For example:

// An input with a name attribute equal to 'MyModel[title]' is accessible at
$title = $this->request->getData('MyModel.title');

You can get value of $id variable like this:

$id = $this->request->getData('id');

Further Reading: Request Body Data

Sehdev
  • 5,486
  • 3
  • 11
  • 34
0

Is this what you want to do?

$id = $this->request->getData('id');
debug($this->Products->get($id)); //for test
Franz
  • 645
  • 1
  • 9
  • 21