CakePHP 3 edit form isn't being populated with database object

80 Views Asked by At

I've built a fair number of applications in CakePHP which have edit (Update) functionality. I've come across an issue which I haven't had before where Cake isn't populating a set of form fields even though the data is being returned from the database and the field names match.

In a Controller method I am obtaining data:

public function edit() 
{
    $invno = '1234'; // This is dynamic from the URL but is here for the example

    $TblInvoicestobepaid = TableRegistry::getTableLocator()->get('TblInvoicestobepaid');
    $data = $TblInvoicestobepaid->find()->where(
            ['invno' => $invno]
        );
    if (!$data->isEmpty()) {
        $data = $data->first();
    }

}

If I do debug($data); I can see that the data is being returned from the database and is an Object:

object(App\Model\Entity\TblInvoicestobepaid) {

'invno' => '1234',
'amount' => '1090',
'vat' => '218',
'total' => '1308',
'orgname' => 'Test Company',

}

I have then used $this->set(compact('data')); to pass this data to my template. This seems the same as other Controller edit() methods including those that have been baked.

I'm using the Form Helper and the field names match the keys in the object above, e.g.

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

<?php echo $this->Form->text('invno'); ?>
<?php echo $this->Form->text('amount'); ?>
<?php echo $this->Form->text('vat'); ?>
<?php echo $this->Form->text('total'); ?>
<?php echo $this->Form->text('orgname'); ?>

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

The form is rendered but the fields are empty.

One thing I did notice is that this is a legacy application and the table where this data is obtained from doesn't have an id field. The Primary Key is invno and this is a string (varchar in MySQL). But this has been defined in the Table class:

// src/Model/Table/TblInvoicestobepaidTable.php
public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('tbl_invoicestobepaid');
    $this->setDisplayField('invno');
    $this->setPrimaryKey('invno');
}

I don't have any problems inserting data through the add() method in my Controller. But when it comes to editing it's not populating the form, and I don't understand why.

CakePHP version is 3.8.12

0

There are 0 best solutions below