TimeField null values - help please

<%- if @topic_view.topic.tags.present? %>
<%= t 'js.tagging.tags' %>: <%- @topic_view.topic.tags.each do |t| %> <%= t %> <%- end %>
<% end %>

I am trying to leave the TimeField as null on an admin page load if null in the database but it always defaults to midnight (00:00:00). When I save the page again this value of midnight gets saved to the database which is undesirable.

Is there a method of achieving this?

I found the reason why it is happening below.

class TimeField extends TextField
{
public function Value()
{
    $localised = $this->internalToFrontend($this->value);
    if ($localised) {
        return $localised;
    }

    // Show midnight in localised format
    return $this->getMidnight();
}

I’m not sure where I found this originally, so I’m not sure who to credit, but I ran into that issue as well. What worked for me was grabbing Shea Dawson’s TimePickerField addon - GitHub - sheadawson/silverstripe-timepickerfield: A time picker field based on jQuery UI Timepicker By François Gélinas then extending it like this…

<?php

use SheaDawson\TimePickerField\TimePickerField;

class NullableTimeField extends TimePickerField
{

// This fixes the default midnight stuff
public function Value()
{
    $localised = $this->internalToFrontend($this->value);
    if ($localised) {
        return $localised;
    }

    return '';
}

}

Thanks Andrew. I ended up extending the standard TimeField.

use SilverStripe\Forms\TimeField;

class NullableTimeField extends TimeField
{
	// This fixes the default midnight stuff
    public function Value()
    {
        $localised = $this->internalToFrontend($this->value);
        if ($localised) {
            return $localised;
        }

        // Show empty format
		return '';
    }
}

If you also need to use it on Symbiote\GridFieldExtensions\GridFieldEditableColumns

silverstripe-gridfieldextensions/index.md at 3 · symbiote/silverstripe-gridfieldextensions · GitHub

$grid = GridField::create(
...
);
  $grid->getConfig()->getComponentByType(GridFieldEditableColumns::class)->setDisplayFields(array(
	'StartDate' => array(
		'title' => 'Start Date',
		'field' => 'SilverStripe\Forms\DateField'
	),
	'EndDate' => array(
		'title' => 'End Date',
		'field' => 'SilverStripe\Forms\DateField'
	),
	'StartTime' => array(
		'title' => 'Start Time',
		'field' => 'NullableTimeField'
	),
	'EndTime' => array(
		'title' => 'End Time',
		'field' => 'NullableTimeField'
	)
));
1 Like