CrugeField.php 8.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
<?php
/**
 * CrugeField
 *
 * @property integer $idfield
 * @property string $fieldname
 * @property string $longname
 * @property integer $position
 * @property integer $required
 * @property integer $fieldtype
 * @property integer $fieldsize
 * @property integer $maxlength
 * @property integer $showinreports  si este campo es visible en listas de usuario del administrador
 * @property string $useregexp    expresion regular, dejar en blanco si no se usa.
 * @property string $useregexpmsg    mensaje cuando la expresion regular falla
 * @property string $predetvalue    valor predeterminado, usado ademas para llenar listas de opcion
 *
 * @uses CActiveRecord
 * @author: Christian Salazar H. <christiansalazarh@gmail.com> @salazarchris74
 * @license protected/modules/cruge/LICENSE
 */
class CrugeField extends CActiveRecord
    implements ICrugeField
    //,IModelErrorReport
{


    private $_value;
    private $_errors;

    /*
        debido a que varios atributos aqui son sensibles los espacios entonces
        se les hara trim a todos.
    */
    public function onBeforeValidate($event)
    {
        foreach ($this->getIterator() as $atributo => $valor) {
            $this[$atributo] = trim($valor);
        }
    }


    /*
        devuelve un objeto que implementa a ICrugeField
    */
    public static function loadModel($id)
    {
        return self::model()->findByPk($id);
    }

    public static function loadModelByName($name)
    {
        return self::model()->findByAttributes(array('fieldname' => $name));
    }

    /* entrega un array con los nombres de los atributos clave para orden,
        colocar de primero el primaryKey
    */
    public static function getSortFieldNames()
    {
        return array('fieldname', 'longname', 'required');
    }

    public function getRequiredName()
    {
        if ($this->required == 1) {
            return CrugeTranslator::t("Si");
        }
        return CrugeTranslator::t("");
    }

    /**
    devuelve un array de objetos que implementan a ICrugeField
     */
    public static function listModels()
    {
        return self::model()->findAllByAttributes(array(), array('order' => 'position ASC'));
    }

    public function setFieldValue($value)
    {
        $this->_value = $value;
    }

    public function getFieldValue()
    {
        return $this->_value;
    }

    /*
        pregunta si este campo es visible en listas de usuario del administrador
    */
    public function isVisibleInAdminList()
    {
        return $this->showinreports == 1;
    }

    /*
        hace una validacion de este campo
    */
    public function validateField()
    {

        $validateResult = true;
        $_val = trim($this->getFieldValue());

        if (($_val == "") && ($this->required != 0)) {
            $validateResult = false;
            $this->addError(
                $this->fieldname
                ,
                CrugeTranslator::t("este campo es requerido") . ". [" . $this->longname . "]"
            );
        }

		if($this->maxlength != -1)
        if (strlen($_val) > $this->maxlength) {
            $validateResult = false;
            $this->addError(
                $this->fieldname
                ,
                CrugeTranslator::t("el tamano maximo permitido es")
                    . $this->maxlength . " " . CrugeTranslator::t("caracteres o digitos")
                    . ". [" . $this->longname . "]"
            );
        }


        if ((trim($this->useregexp) != "") && (trim($this->getFieldValue()) != "")) {
            // aplica regexp segun el usuario haya configurado el campo
            if (preg_match("/" . trim($this->useregexp) . "/", $this->getFieldValue())) {
                // todo bien
            } else {
                $validateResult = false;
                $this->addError(
                    $this->fieldname
                    ,
                    CrugeTranslator::t($this->useregexpmsg)
                );
            }
        }

        return $validateResult;
    }

    /**
    retorna el nombre de la tabla
     */
    public function tableName()
    {
        return CrugeUtil::getTableName("field");
    }

    /*
        devuelve "el valor" del indice primario
    */
    public function getPrimaryKey()
    {
        return $this->idfield;
    }


    /**
     * Returns the static model of the specified AR class.
     * @return CrugeField the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }


    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(

            array('fieldname', 'length', 'max' => 20),
            array('longname', 'length', 'max' => 50),
            array('useregexp', 'length', 'max' => 512),
            array('useregexpmsg', 'length', 'max' => 512),
            array('predetvalue', 'length', 'max' => 4096),
            array(
                'fieldname',
                'match'
            ,
                'pattern' => '/^([a-zA-Z]{3,20})$/'
            ,
                'message' => CrugeTranslator::t("solo use de 3 a 20 letras (a-z), sin espacios")
            ),
            array(
                'position, required, fieldtype, fieldsize, maxlength, showinreports'
            ,
                'numerical',
                'integerOnly' => true
            ),
            array(
                'fieldname, longname, fieldtype, fieldsize, maxlength'
            ,
                'required'
            ),
            array('fieldname', 'unique'),
            array('position', 'numerical', 'min' => 0, 'max' => 99),
            array('fieldsize', 'numerical', 'min' => 1, 'max' => 100),
            array('maxlength', 'numerical', 'min' => -1, /*'max' => 512*/),
            array('predetvalue', 'safe'),
            array('idfield, fieldname, longname, position, required, fieldtype', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array();
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'idfield' => 'Idfield',
            'fieldname' => ucwords(CrugeTranslator::t('Nombre Interno')),
            'longname' => ucwords(CrugeTranslator::t('Nombre Publico')),
            'position' => ucwords(CrugeTranslator::t('Posicion')),
            'required' => ucwords(CrugeTranslator::t('Requerido')),
            'fieldtype' => ucwords(CrugeTranslator::t('Tipo')),
            'fieldsize' => ucwords(CrugeTranslator::t('Ancho Caracteres')),
            'maxlength' => ucwords(CrugeTranslator::t('Longitud Maxima')),
            'showinreports' => ucwords(CrugeTranslator::t('Ver en Reportes')),
            'useregexp' => ucwords(CrugeTranslator::t('Expresion Regular')),
            'useregexpmsg' => ucwords(CrugeTranslator::t('Mensaje de error')),
            'predetvalue' => ucwords(CrugeTranslator::t('Valor Predeterminado / Opciones de Lista')),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('idfield', $this->idfield);
        $criteria->compare('fieldname', $this->fieldname, true);
        $criteria->compare('longname', $this->longname, true);
        $criteria->compare('position', $this->position);
        $criteria->compare('required', $this->required);
        $criteria->compare('fieldtype', $this->fieldtype);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'sort' => array(
                'defaultOrder' => array('position' => false),
            ),
        ));
    }
}