Skip to content

Commit

Permalink
fixed issue #5
Browse files Browse the repository at this point in the history
  • Loading branch information
lee-to committed Jun 16, 2022
1 parent cedf554 commit eed530d
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/Fields/Date.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,17 @@ class Date extends Field

public function formViewValue(Model $item): string
{
if(!$this->getDefault() && $this->isNullable()) {
return '';
}

return date('Y-m-d', strtotime($item->{$this->name()} ?? $this->getDefault()));
}

public function indexViewValue(Model $item, bool $container = false): string
{
return date($this->format, strtotime($item->{$this->name()}));
return $item->{$this->name()}
? date($this->format, strtotime($item->{$this->name()}))
: '';
}
}
2 changes: 1 addition & 1 deletion src/Fields/Field.php
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ public function save(Model $item): Model
{
$item->{$this->field()} = $this->requestValue() !== false
? $this->requestValue()
: '';
: ($this->isNullable() ? null : '');

return $item;
}
Expand Down
74 changes: 74 additions & 0 deletions tests/Fields/DateTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

namespace Leeto\MoonShine\Tests\Fields;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Leeto\MoonShine\Fields\Date;
use Leeto\MoonShine\Models\MoonshineUser;
use Leeto\MoonShine\Resources\MoonShineUserResource;
use Leeto\MoonShine\Tests\TestCase;

class DateTest extends TestCase
{
use RefreshDatabase;

public function test_values()
{
$user = MoonshineUser::factory()->make([
'created_at' => '2022-01-01 00:00:00'
]);

$field = Date::make('Created at')
->format('d.m.Y');

$this->assertEquals('2022-01-01', $field->formViewValue($user));
$this->assertEquals('01.01.2022', $field->indexViewValue($user));
}

public function test_nullable()
{
$user = new MoonshineUser();

$field = Date::make('Created at')
->nullable();

$this->assertEquals('', $field->formViewValue($user));
$this->assertEquals('', $field->indexViewValue($user));
}

public function test_default()
{
$user = new MoonshineUser();

$field = Date::make('Created at')
->default('2022-01-02');

$this->assertEquals('2022-01-02', $field->formViewValue($user));

$field = Date::make('Created at')
->nullable()
->default('2022-01-02');

$this->assertEquals('2022-01-02', $field->formViewValue($user));
}

public function test_save()
{
$user = new MoonshineUser();

$field = Date::make('Created at')
->default('2022-01-02');

$item = $field->save($user);

$this->assertEquals('2022-01-02', $item->created_at->format('Y-m-d'));

$field = Date::make('Created at')
->nullable();

$item = $field->save($user);

$this->assertNull($item->created_at);

}
}

0 comments on commit eed530d

Please sign in to comment.