kartik datepicker cannot initialise to default ('0000-00-00')

date cannot initialise to default (‘0000-00-00’)

I have a kartik datepicker which presents the following error on save

Database Exception – yii\db\Exception

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: ‘<span class=“not-set”>(not set)</span>’ for column ‘date_of_birth’ at row 1

The SQL being executed was: INSERT INTO registration (firstname, email, telephone, box_no, postal_code, town, home_address, home_number, type, date_of_birth) VALUES (‘w.w. Sires’, ‘’, ‘0722339988’, ‘’, ‘’, ‘Nairobi’, ‘’, ‘’, ‘2’, ‘<span class=\“not-set\”>(not set)</span>’)

Error Info: Array

(

[0] =&gt; 22007


[1] =&gt; 1292


[2] =&gt; Incorrect date value: '(not set)' for column 'date_of_birth' at row 1

)

I have tried the following in vain

_form.php

<?php

// Usage with model (with no default initial value)

echo ‘<label class=“control-label”>Birth Date</label>’;

echo DatePicker::widget([

'model' =&gt; &#036;model, 


'attribute' =&gt; 'date_of_birth',


'value' =&gt; '0000-00-00',


'options' =&gt; ['placeholder' =&gt; 'Enter Date Of Birth ...'],


'pluginOptions' =&gt; [


    'autoclose'=&gt;true,


	'format' =&gt; 'dd-M-yyyy'


]

]);

?>

Registration model

public function rules()


{


    return [


		[['date_of_birth'], 'default', 'value' =&gt; '0000-00-00'], //if not set enter '0000-00-00'


		['date_of_birth', 'compare', 'compareValue' =&gt; 18, 'operator' =&gt; '&gt;='],		//if set ensure itss &gt; 18yrs	


    ];


}

Have you tried with:




      [['date_of_birth'], 'default', 'setOnEmpty' => true, 'value' => '0000-00-00'],



‘0000-00-00’ is indeed an invalid datetime format - your database is right.

Either set a different default value, or don’t set anything at all - provided that NULLs are allowed.

Solved::

didnt work, maybe my yii2 version - [[‘date_of_birth’], ‘default’, ‘setOnEmpty’ => true, ‘value’ => ‘0000-00-00’],

Somehow when using scenarios, a date object is not set , so solution was in

     function  beforeSave {


	if (&#036;this-&gt;date_of_birth == null || &#33;defined(&#036;this-&gt;date_of_birth)) {


		&#036;this-&gt;date_of_birth = null;


		//echo 'date_of_birth: '.&#036;this-&gt;date_of_birth.&quot;&lt;br&gt;isnull&quot;;


	}

SOLVED::

this never worked. Maybe my yii2 version

[[‘date_of_birth’], ‘default’, ‘setOnEmpty’ => true, ‘value’ => ‘0000-00-00’],

Using scenarios, the date object which was removed was not set.

solution in beforeSave function

	if (&#036;this-&gt;date_of_birth == null || &#33;defined(&#036;this-&gt;date_of_birth)) {


		&#036;this-&gt;date_of_birth = null;


		//echo 'date_of_birth: '.&#036;this-&gt;date_of_birth.&quot;&lt;br&gt;isnull&quot;;


	}