Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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!



83.4k
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