nova-page icon indicating copy to clipboard operation
nova-page copied to clipboard

Cast Date Field

Open packytagliaferro opened this issue 4 years ago • 3 comments

How do you add a date field with this package? You need to cast the filed as a date so not sure where to put it since there is no model?

Date::make('Delivery')
                ->format('dddd, MMM DD YYYY')
                ->pickerDisplayFormat('m-d-Y')
                ->rules('required'),

returns the error Date field must be casts as Date in eloquent model

packytagliaferro avatar Jun 23 '21 17:06 packytagliaferro

How can we solve this issue?

MannikJ avatar Apr 14 '22 09:04 MannikJ

Hey anyone reading this;

I fixed it by extending the DateTime field and casting it;

use Carbon\Carbon;
use Laravel\Nova\Fields\DateTime as NovaDateTime;

class DateTime extends NovaDateTime
{
    public function __construct($name, $attribute = null, $resolveCallback = null)
    {
        parent::__construct($name, $attribute, function ($value) {
            if ($value && is_string($value)) {
                try {
                    $possible_date = Carbon::createFromFormat('Y-m-d H:i:s', $value);
                    if ($possible_date) {
                        $value = $possible_date;
                    }
                } catch (\Exception $e) {
                    return null;
                }
            }

            return $value;
        });
    }
}

GarethSomers avatar Jun 20 '22 04:06 GarethSomers

I've tried extending the DateTime field as @GarethSomers did which removes the error but formats the data in a way that means it does not appear at all in the form or on the details page after saving. So instead I just overwrote the constructor method to remove the casting check:

<?php

namespace App\Nova\Fields;

class DateTime extends \Laravel\Nova\Fields\DateTime 
{
    /**
     * Create a new field.
     *
     * @param  string  $name
     * @param  string|null  $attribute
     * @param  mixed|null  $resolveCallback
     * @return void
     */
    public function __construct($name, $attribute = null, callable $resolveCallback = null)
    {
        parent::__construct($name, $attribute, $resolveCallback ?? function ($value, $request) {
            return $value;
        });
    }
}

Not entirely happy with this solution as I assume there's a good reason for the check but it's the best I can do for now. Would be great if someone knows how to resolve the underlying problem, because currently this package simply doesn't support DateTIme fields.

jolora avatar Oct 18 '23 06:10 jolora