We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Custom behavior

I wrote custom type of behavior to my project needs. It's looks like this:

<?php
namespace Ely\Behavior;

use Phalcon\Mvc\Model\Behavior;
use Phalcon\Mvc\Model\BehaviorInterface;

class IPStampable extends Behavior implements BehaviorInterface {
    public function notify($type, $model) {
        $options = $this->getOptions();
        if (array_key_exists($type, $options)) {
            $options = $options[$type];
            $model->$options['field'] = \Phalcon\DI::getDefault()->getRequest()->getClientAddress();
        }
    }
}

But when i try to do this (in model initialize() method):

$this->addBehavior(new Timestampable(array(
    "beforeValidationOnCreate" => array(
        "field" => "registered"
    )
)));
$this->addBehavior(new IPStampable(array(
    "beforeValidationOnCreate" => array(
        "field" => "reg_ip"
    )
)));

I still get "reg_ip is required", but I checked - the value is set

I have a version of what is happening. Field reg_ip in DB have type as int(10) unsigned and when i set value as ip generate the string (pro english, yep). I maked get\set and now model looks like this:

protected $reg_ip;

public function getRegIp() {
    return long2ip($this->reg_ip);
}

public function setRegIp($ip) {
    $this->reg_ip = ip2long($ip);
}

public function initialize() {
    $this->addBehavior(new IPStampable(array(
        "beforeValidationOnCreate" => array(
            "field" => "regIp"
        )
    )));
}

But I still can't save the model!



98.9k
Accepted
answer

Property $reg_ip is protected so it can't be assigned directly, you have to use the setter or writeAttribute:

$model->writeAttribute($options['field'], \Phalcon\DI::getDefault()->getRequest()->getClientAddress());

Yep, this help me