Yii Framework Forum: [RESUELTO]campo fecha opcional - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

[RESUELTO]campo fecha opcional Rate Topic: -----

#1 User is offline   gallego123 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 535
  • Joined: 11-August 09
  • Location:Argentina

Posted 23 September 2009 - 06:30 AM

Hola

tengo un problema

cuando actualizo un campo fecha opcional con el valor nulo
me almacena "0000-00-00" en lugar de dejar vacio el campo

y si uso la extension i18n-datetime-behavior
me almacena 31/12/1969

help
KISS - Keep It Simple Stupid
ASAP-As Soon As Possible
http://www.yiiframew...oc/cookbook/71/
0

#2 User is offline   sebas 

  • Advanced Member
  • Yii
  • Group: Yii Dev Team
  • Posts: 495
  • Joined: 28-October 08
  • Location:Buenos Aires, Argentina

Posted 23 September 2009 - 07:44 AM

View PostHoracio Segura, on 23 September 2009 - 06:30 AM, said:

Hola

tengo un problema

cuando actualizo un campo fecha opcional con el valor nulo
me almacena "0000-00-00" en lugar de dejar vacio el campo

y si uso la extension i18n-datetime-behavior
me almacena 31/12/1969

help


Lo tenes habilitado para null?? A veces en mysql cuando pones en null algo y no tiene el allow null pone 0.

Saludos,
0

#3 User is offline   gallego123 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 535
  • Joined: 11-August 09
  • Location:Argentina

Posted 23 September 2009 - 08:29 AM

View Postsebas, on 23 September 2009 - 07:44 AM, said:

Lo tenes habilitado para null?? A veces en mysql cuando pones en null algo y no tiene el allow null pone 0.

Saludos,



Hola Sebas
si, es un campo opcional (campo fecha_estado)

CREATE TABLE IF NOT EXISTS `Rp_profesionales` (
  `idProfesional` int(11) NOT NULL auto_increment,
  `cod_profesional` varchar(45) collate utf8_unicode_ci default NULL COMMENT 'se deja solo para consulta, es la clave primaria anterior.\nlibro + matricula principal',
  `are_idArea` int(11) NOT NULL,
  `estado` varchar(45) collate utf8_unicode_ci NOT NULL COMMENT 'dominio, por defecto = 1= Activo',
  `fecha_estado` date default NULL,
  `motivo_estado` varchar(45) collate utf8_unicode_ci default NULL COMMENT 'es un dominio ',
  `obs` varchar(500) collate utf8_unicode_ci default NULL,
  `fecha` date NOT NULL,
  `per_idPersona` int(11) NOT NULL COMMENT 'solo una persona puede estar activa',
  PRIMARY KEY  (`idProfesional`),
  KEY `pro_are_fk` (`are_idArea`),
  KEY `pro_per_fk` (`per_idPersona`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ;

KISS - Keep It Simple Stupid
ASAP-As Soon As Possible
http://www.yiiframew...oc/cookbook/71/
0

#4 User is offline   PoL 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 506
  • Joined: 05-November 08
  • Location:Buenos Aires, Argentina

Posted 23 September 2009 - 08:49 AM

en rules() creo qpodes poner un valor por defecto...

algo asi como


public function rules(){
return array(

array('fecha_estado', 'default'=>null),


);

}

No lo probe, pero creo que es asi... sino podes hacer tu propio validador... o sobreescribir beforeSave()...
Don't say what you think, think what you say
The problem is communication! Excess of communication!
0

#5 User is offline   gallego123 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 535
  • Joined: 11-August 09
  • Location:Argentina

Posted 23 September 2009 - 09:46 AM

View PostPoL, on 23 September 2009 - 08:49 AM, said:

en rules() creo qpodes poner un valor por defecto...

algo asi como


public function rules(){
return array(

array('fecha_estado', 'default'=>null),


);

}

No lo probe, pero creo que es asi... sino podes hacer tu propio validador... o sobreescribir beforeSave()...



Hola Pol
la extension DateTimeI18NBehavior lo hace
pero tiene un bug cuando son campos opcionales (no obligatorios)

intente ver el error, pero no .... me falta un poco para eso
podrias chequearlo ? gracias


<?php

/*
 * DateTimeI18NBehavior
 * Automatically converts date and datetime fields to I18N format
 * 
 * Author: Ricardo Grana <rickgrana@yahoo.com.br>, <ricardo.grana@pmm.am.gov.br>
 */

class DateTimeI18NBehavior  extends CActiveRecordBehavior
{
	public $dateOutcomeFormat = 'Y-m-d';
	public $dateTimeOutcomeFormat = 'Y-m-d H:i:s';

	public $dateIncomeFormat = 'yyyy-MM-dd';
	public $dateTimeIncomeFormat = 'yyyy-MM-dd hh:mm:ss';

	public function beforeSave($event){
		
		//search for date/datetime columns. Convert it to pure PHP date format
		foreach($event->sender->tableSchema->columns as $columnName => $column){
			if ($column->dbType == 'date'){
				$event->sender->$columnName = date($this->dateOutcomeFormat, CDateTimeParser::parse($event->sender->$columnName, Yii::app()->locale->dateFormat));
			}elseif ($column->dbType == 'datetime'){
				$event->sender->$columnName = date($this->dateTimeOutcomeFormat, CDateTimeParser::parse($event->sender->$columnName, Yii::app()->locale->dateFormat));
			}			
			
		}

		return true;
	}
	
	public function afterFind($event){
					
		foreach($event->sender->tableSchema->columns as $columnName => $column){
			
			
			if (!strlen($event->sender->$columnName)) continue; // if empty, ignore everyelse
			
			if ($column->dbType == 'date'){				
				$event->sender->$columnName = Yii::app()->dateFormatter->formatDateTime(
								CDateTimeParser::parse($event->sender->$columnName, $this->dateIncomeFormat),'medium',null);
			}elseif ($column->dbType == 'datetime'){
				$event->sender->$columnName = Yii::app()->dateFormatter->formatDateTime(
								CDateTimeParser::parse($event->sender->$columnName, $this->dateTimeIncomeFormat));
			}
		}
		return true;
	}
}

KISS - Keep It Simple Stupid
ASAP-As Soon As Possible
http://www.yiiframew...oc/cookbook/71/
0

#6 User is offline   PoL 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 506
  • Joined: 05-November 08
  • Location:Buenos Aires, Argentina

Posted 23 September 2009 - 09:51 AM

Podes postear tu codigo...
Para ver como estas usando ese behavior... etc....

En cuanto al codigo ese que posteaste antes tendrias que preguntarle mejor al muchacho que lo hizo
Author: Ricardo Grana <rickgrana@yahoo.com.br>, <ricardo.grana@pmm.am.gov.br>

Don't say what you think, think what you say
The problem is communication! Excess of communication!
0

#7 User is offline   PoL 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 506
  • Joined: 05-November 08
  • Location:Buenos Aires, Argentina

Posted 23 September 2009 - 10:03 AM

Definitivamente podes usar default en rules

Esto dijo master qiang:

Quote

Ok, feature is implemented.
You can use a rule in rules() to set a default value:


array('attr1, attr2', 'default', 'value'=>'something')


Since you can specify an 'on' option in a rule, this would allow an attribute to be set with different default values in different scenarios.

For SQL functions like NOW, you can do this:


array('attr1, attr2', 'default', 'value'=>new CDbExp​ression('NOW()'))

Don't say what you think, think what you say
The problem is communication! Excess of communication!
0

#8 User is offline   gallego123 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 535
  • Joined: 11-August 09
  • Location:Argentina

Posted 23 September 2009 - 10:18 AM

View PostPoL, on 23 September 2009 - 09:51 AM, said:

Podes postear tu codigo...
Para ver como estas usando ese behavior... etc....

En cuanto al codigo ese que posteaste antes tendrias que preguntarle mejor al muchacho que lo hizo
Author: Ricardo Grana <rickgrana@yahoo.com.br>, <ricardo.grana@pmm.am.gov.br>




en el model puse la funcion y nada mas(no hay codigo extraño ni en la vista ni en el controlador)

public function behaviors()
{
    return array(
        // Classname => path to Class
        'datetimeI18NBehavior' => 'application.behaviors.DateTimeI18NBehavior',
    );
}


ya me contacte con el autor.... pero no lo solucionó aún
KISS - Keep It Simple Stupid
ASAP-As Soon As Possible
http://www.yiiframew...oc/cookbook/71/
0

#9 User is offline   PoL 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 506
  • Joined: 05-November 08
  • Location:Buenos Aires, Argentina

Posted 23 September 2009 - 10:34 AM

Lo unico que se me ocurre es que intentes usar esto:

<?php 
   public function rules(){
      return array(
         // otras reglas...
         array('fecha_estado', 'default', 'value'=>null),
      );
   }


Don't say what you think, think what you say
The problem is communication! Excess of communication!
0

#10 User is offline   gallego123 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 535
  • Joined: 11-August 09
  • Location:Argentina

Posted 23 September 2009 - 10:38 AM

encontre algo sobre la fecha 31/12/1969
"El mktime trabaja con fechas a partir de 1970 ..."


yo mismo me vote en contra
KISS - Keep It Simple Stupid
ASAP-As Soon As Possible
http://www.yiiframew...oc/cookbook/71/
-1

#11 User is offline   gallego123 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 535
  • Joined: 11-August 09
  • Location:Argentina

Posted 23 September 2009 - 10:39 AM

View PostPoL, on 23 September 2009 - 10:34 AM, said:

Lo unico que se me ocurre es que intentes usar esto:

<?php 
   public function rules(){
      return array(
         // otras reglas...
         array('fecha_estado', 'default', 'value'=>null),
      );
   }




ok, gracias!
KISS - Keep It Simple Stupid
ASAP-As Soon As Possible
http://www.yiiframew...oc/cookbook/71/
0

#12 User is offline   gallego123 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 535
  • Joined: 11-August 09
  • Location:Argentina

Posted 23 September 2009 - 03:15 PM

bien, modifique un poco la extension y salio esto

<?php

class DateBehavior_beta  extends CActiveRecordBehavior
{

	public function dateconvert($date,$func) {
		
		if ($date =='00/00/0000' or  $date ==null) return null;
		if ($func == 1){ //insert conversion
			list($day, $month, $year) = split('[/.-]', $date);
			$date = "$year-$month-$day";
			return $date;
		}
		if ($func == 2){ //output conversion
			list($year, $month, $day) = split('[-.]', $date);
			$date = "$day/$month/$year";
			return $date;
        }
    }
	
	
	public function beforeSave($event){

		//search for date/datetime columns. Convert it to pure PHP date format
		foreach($event->sender->tableSchema->columns as $columnName => $column){
			if ($column->dbType == 'date')
				$event->sender->$columnName = $this->dateconvert($event->sender->$columnName,1);
			}
		    return true;
	   }
	
	
	public function afterFind($event){
					
		foreach($event->sender->tableSchema->columns as $columnName => $column){
			
			
			if (!strlen($event->sender->$columnName)) continue; // if empty, ignore everyelse
			
			if ($column->dbType == 'date')				
				$event->sender->$columnName = $this->dateconvert($event->sender->$columnName,2);
		}
		return true;
	}
	

}
?>


en el model
public function behaviors()
{
    return array('DateBehavior_beta' => array('class' => 'DateBehavior_beta')); 
}

solo sirve para fechas (no fecha y hora)
KISS - Keep It Simple Stupid
ASAP-As Soon As Possible
http://www.yiiframew...oc/cookbook/71/
0

#13 User is offline   gallego123 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 535
  • Joined: 11-August 09
  • Location:Argentina

Posted 29 September 2009 - 10:53 AM

Solucion final
funciones utilies
       /* Agrega / a la fecha*/
       public static function agregarBarras($date_in) {

        $date_out=$date_in;
        $date_aux = str_replace(array('\'', '-', '.', ','), '/', $date_in);
        $date_arr = explode('/', $date_aux);

        if(count($date_arr) == 1 and strlen($date_arr[0])== 8) // No tokens
            {
                $date_out=substr($date_arr[0], 0, 2).'/'.substr($date_arr[0], 2, 2).'/'.substr($date_arr[0], 4, 4);
            }
        elseif(count($date_arr) == 1 and strlen($date_arr[0])== 6) // No tokens
            {
                $date_out=substr($date_arr[0], 0, 2).'/'.substr($date_arr[0], 2, 2).'/'.substr($date_arr[0], 4, 2);
            }

        return $date_out;

    }
    /*retorna si la fecha ingresada es una fecha
     *  acepta fechas separadas por . - y /
     * ademas acepta una fecha como 20062009 = 20/06/2009
     */
    public static function is_date($date)
    {
     try {
        $date = str_replace(array('\'', '-', '.', ','), '/', $date);
        $date = explode('/', $date);


        if(    count($date) == 3
            and    is_numeric($date[0])
            and    is_numeric($date[1])
            and    is_numeric($date[2])
            and    checkdate($date[1], $date[0], $date[2])
            //(    checkdate($date[0], $date[1], $date[2]) //mmddyyyy
            //or   checkdate($date[1], $date[0], $date[2]) //ddmmyyyy
            //or   checkdate($date[1], $date[2], $date[0]))//yyyymmdd
        )
        {
            return true;
        }


        if(    count($date) == 1 // No tokens  10022006
            and    is_numeric($date[0])
            and    strlen($date[0])== 8 and
            (    checkdate(substr($date[0], 2, 2)
                        , substr($date[0], 0, 2)
                        , substr($date[0], 4, 4)))
        )
        {
            return true;
        }

        if(    count($date) == 1 // No tokens  10022006
            and    is_numeric($date[0])
            and    strlen($date[0])== 6 and
            (    checkdate(substr($date[0], 2, 2)
                        , substr($date[0], 0, 2)
                        , substr($date[0], 4, 2)))
        )
        {
            return true;
        }



        return false;
    }
        catch(Exception $e) {return false;};
    }


        public function dateconvert($date,$func) {

                if ($date =='00/00/0000' or  $date ==null) return null;
                if ($func == 1){ //insert conversion
                        list($day, $month, $year) = split('[/.-]', $date);
                        //si ingresa 10/8/9, pongo 10/08/09, sino me pone 0009 en vez de 2009
                        if (strlen($year)==1) $year='0'.$year;

                        $date = "$year-$month-$day";
                        return $date;
                }
                if ($func == 2){ //output conversion
                        list($year, $month, $day) = split('[-.]', $date);
                        $date = "$day/$month/$year";
                        return $date;
        }
    }



cree un validator
validator


y uso datetimeI18Nbehavior pero modificado
class DateTimeI18NBehavior  extends CActiveRecordBehavior
{




        public function beforeSave($event){

                //search for date/datetime columns. Convert it to pure PHP date format
                foreach($event->sender->tableSchema->columns as $columnName => $column){
                        if ($column->dbType == 'date')
                                $event->sender->$columnName = Varios::dateconvert($event->sender->$columnName,1);
                        }
                    return true;
           }


        public function afterFind($event){

                foreach($event->sender->tableSchema->columns as $columnName => $column){


                        if (!strlen($event->sender->$columnName)) continue; // if empty, ignore everyelse

                        if ($column->dbType == 'date')
                                $event->sender->$columnName = Varios::dateconvert($event->sender->$columnName,2);
                }
                return true;
        }

}



espero que le sirva a alguien

la extension fue actualizada
i18n-datetime-behavior

This post has been edited by Horacio Segura: 30 September 2009 - 07:07 AM

KISS - Keep It Simple Stupid
ASAP-As Soon As Possible
http://www.yiiframew...oc/cookbook/71/
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users