SIlverStripe - No data written onBeforeWrite

落爺英雄遲暮 提交于 2019-12-10 12:14:09

问题


Related to this issue, a DataObject extended with onBeforeWrite method doesn't write a specific property value on DB. In detail:

DataObject:

[...] 
/**
 * Classe Prodotto
 */
class Prodotto extends DataObject
{
// Dichiarazione Proprietà
private static $db = [
    [...] 
    'PrezzoIva' => 'Currency',
    [...] 

onBeforeWrite method:

/**
     * Metodo gestione azioni salvataggio
     * Calcolo automatico prezzo lordo e scontato
     * Setter
     * @return void
     */
    public function onBeforeWrite()
    {
        // Controllo Record
        if (!$this->isInDb()) {
            $this->setPrezzoIva();
        }
        if ((!isset($this->record['PrezzoIva'])) || ($this->record['PrezzoIva'] == 0)) {
            $this->setPrezzoIva();
        }

        parent::onBeforeWrite();
    }

The method called by the one above:

/**
     * Metodo calcolo prezzo lordo IVA
     * Setter
     * @return void
     */
    public function setPrezzoIva()
    {
        // Controllo IVA
        if ((isset($this->PrezzoIva)) && ($this->PrezzoIva == 0)) {
            $prezzoIva = ($this->PrezzoUnitario * $this->Iva) + $this->PrezzoUnitario;

            // Salvataggio IVA
            $this->PrezzoIva = $prezzoIva;
        }
    }

There's no exception thrown. Basically, both on the first write() as well as in other saves, PrezzoIva is not being updated (it keeps the default one). Here an extract to my DB after few DataObject edits:

For now, I not figured out what causing this. A help of any kind will be appreciated.

Thanks in advance everyone.


回答1:


You have to watch the setters in SilverStripe. SilverStripe uses the __set function.

When you call $this->PrezzoIva it will search for a method called setPrezzoIva. If it cannot find a method with that name, it will call the method setField. Which will actually set the field like you want.

So the problem you're experiencing is because your method is called setPrezzoIva. Instead of setting the value, it is excecuting your method.

To fix this, change

$this->PrezzoIva = $prezzoIva;

to

$this->setField('PrezzoIva', $prezzoIva);

On a sidenote, I think Robbie is right, your conditions are too strict.




回答2:


For some unknown reason, renaming the property involved with a different name, solved the issue. The only cause that I could assume for good, Is that it could been caused by the fact that the DataObject has many properties with the same prefix-name (PrezzoIva, PrezzoScontato, PrezzoUnitario, etc.) and, in some mysterious way, was confunding the value/proper field association.



来源:https://stackoverflow.com/questions/49903348/silverstripe-no-data-written-onbeforewrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!