Jump to content

Override product field on save using hooks


Recommended Posts

Hello everyone, I'm writing my first module and for that I need to update the product reference during the "actionProductSave" hook.

 

Simply overriding the $params, does not seem to work:

public function hookActionProductSave(array $params)
{        
    if (empty($params['reference'])) {
		$params['reference'] = "example";        
    }
}

 

Manually saving product again, would save the new field, but would also abort saving other changes:

public static $executed = false;

public function hookActionProductSave(array $params)
{        
    if (Self::$executed) {
        Self::$executed = false;
    }
    elseif (empty($params['reference'])) {
        Self::$executed = true;
        $product = new Product($params['id_product']);
        $product->reference = "example";
        $product->save();
    }
}

 

Is there any clean way to do this, without overrides?

I'm using MySql, therefore a trigger wouldn't work.

Link to comment
Share on other sites

Minimal sample:


    public function hookActionObjectProductAddAfter($params)
    {
        if ($params['object']->reference == ''){
            $params['object']->reference = $this->generateReference();
            $params['object']->update();
        }  
    }

    public function generatReference()
    {
        $length = 10;
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;   
    }

 

  • Like 1
  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...