whitecube / nova-page

Static pages content management for Laravel Nova
https://whitecube.github.io/nova-page
MIT License
238 stars 41 forks source link

Cast Date Field #82

Open packytagliaferro opened 3 years ago

packytagliaferro commented 3 years ago

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

MannikJ commented 2 years ago

How can we solve this issue?

GarethSomers commented 2 years ago

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;
        });
    }
}
jolora commented 10 months ago

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.