naifalshaye / toggle-switch-field

4 stars 3 forks source link

Doesn't seem to respect tinyint(1) / boolean coming from database #4

Closed ekazda closed 7 months ago

ekazda commented 7 months ago

I have a field in my table called "newsletter". It returns a 1 for true. The field is a tinyint(1) created via a migration script.

This in my detail view for my resource:

Boolean::make('Subscribe To Emails', 'newsletter'),

ToggleSwitchField::make('Subscribe To Emails', 'newsletter'),

For the boolean field, the checkmark box is checked (as expected). For the ToggleSwitchField, it is untoggled/unchecked. I even tried to force it to toggle with the following code...

ToggleSwitchField::make('Subscribe To Emails', 'newsletter')
    ->resolveUsing(function ($value, $resource) {
        return true;
    }),

... and it still does nothing. Does this field actually work or am I doing something wrong?

naifalshaye commented 7 months ago

If it's a boolean datatype it should work without using resolveUsing method, make sure you have a default value

$table->boolean('newsletter')->default(true)->nullable();

ekazda commented 7 months ago

Yep. This is my migration information:

$table->boolean('newsletter')->default(true)->change();

I don't want my field to be nullable. The database returns either a "1" or a "0". When bound to the field as so...

At the top of my resource use Naif\ToggleSwitchField\ToggleSwitchField;

In my fields ToggleSwitchField::make('Subscribe To Emails', 'newsletter')

It always returns unchecked/untoggled in the edit screen. It also attempts to push NULL back into my data, when really this is either true or false.

naifalshaye commented 7 months ago

Hi Ekazda,

Thanks for reporting the issue! It's been fixed now.

Please run composer update to get the latest version.

ekazda commented 7 months ago
Screenshot 2024-01-25 at 5 02 42 PM

This still doesn't seem to work. The screen capture is from my EDIT view.

Here is my code for both fields:

Boolean::make('Subscribe To Emails', 'newsletter'),

ToggleSwitchField::make('Subscribe To Emails', 'newsletter'),

And I did upgrade composer as you directed... below is the output during my upgrade.

- Upgrading naif/toggle-switch-field (1.1.0 => 1.1.2): Extracting archive

naifalshaye commented 7 months ago

I have tested it on multiple projects and it's working.

Please provide me with version number you are using for the below: Laravel Nova Mysql Local server

ekazda commented 7 months ago

MySQL 8.1.0 PHP 8.3.1

ardenthq/nova-image-gallery-field  2.2.0    Field for Nova that allows you to upload multiple images and sort them
brick/math                         0.11.0   Arbitrary-precision arithmetic library
brick/money                        0.8.1    Money and currency library
carbonphp/carbon-doctrine-types    2.1.0    Types to use Carbon in Doctrine
dflydev/dot-access-data            v3.0.2   Given a deep data structure, access data by dot notation.
doctrine/cache                     2.2.0    PHP Doctrine Cache library is a popular cache implementation that supports many different drivers such as redis, memcache, apc, mongodb and others.
doctrine/dbal                      3.7.3    Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.
doctrine/deprecations              1.1.2    A small layer on top of trigger_error(E_USER_DEPRECATED) or PSR-3 logging with options to disable all deprecations or selectively for packages.
doctrine/event-manager             2.0.0    The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.
doctrine/inflector                 2.0.9    PHP Doctrine Inflector is a small library that can perform string manipulations with regard to upper/lowercase and singular/plural forms of words.
doctrine/lexer                     3.0.0    PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.
dragonmantank/cron-expression      v3.3.3   CRON for PHP: Calculate the next or previous run date and determine if a CRON expression is due
egulias/email-validator            4.0.2    A library for validating emails against several RFCs
fakerphp/faker                     v1.23.1  Faker is a PHP library that generates fake data for you.
filp/whoops                        2.15.4   php error handling for cool kids
formfeed-uk/nova-theming-classes   1.1.0    A Laravel Nova package to add theming classes to components.
fruitcake/php-cors                 v1.3.0   Cross-origin resource sharing library for the Symfony HttpFoundation
graham-campbell/result-type        v1.1.2   An Implementation Of The Result Type
guzzlehttp/guzzle                  7.8.1    Guzzle is a PHP HTTP client library
guzzlehttp/promises                2.0.2    Guzzle promises library
guzzlehttp/psr7                    2.6.2    PSR-7 message implementation that also provides common utility methods
guzzlehttp/uri-template            v1.0.3   A polyfill class for uri_template of PHP
hamcrest/hamcrest-php              v2.0.1   This is the PHP port of Hamcrest Matchers
inertiajs/inertia-laravel          v0.6.11  The Laravel adapter for Inertia.js.
intervention/image                 2.7.2    Image handling and manipulation library with support for Laravel integration
laravel/framework                  v10.42.0 The Laravel Framework.
laravel/nova                       4.32.11  A wonderful administration interface for Laravel.
laravel/pint                       v1.13.10 An opinionated code formatter for PHP.
laravel/prompts                    v0.1.15 
laravel/sail                       v1.27.2  Docker files for running a basic Laravel application.
laravel/sanctum                    v3.3.3   Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.
laravel/serializable-closure       v1.3.3   Laravel Serializable Closure provides an easy and secure way to serialize closures in PHP.
laravel/tinker                     v2.9.0   Powerful REPL for the Laravel framework.
laravel/ui                         v4.4.0   Laravel UI utilities and presets.
league/commonmark                  2.4.1    Highly-extensible PHP Markdown parser which fully supports the CommonMark spec and GitHub-Flavored Markdown (GFM)
league/config                      v1.2.0   Define configuration arrays with strict schemas and access values with dot notation
league/flysystem                   3.23.0   File storage abstraction for PHP
league/flysystem-local             3.23.0   Local filesystem adapter for Flysystem.
league/glide                       2.3.0    Wonderfully easy on-demand image manipulation library with an HTTP based API.
league/mime-type-detection         1.14.0   Mime-type detection for Flysystem
maennchen/zipstream-php            3.1.0    ZipStream is a library for dynamically streaming dynamic zip files from PHP without writing to the disk at all on the server.
manogi/nova-tiptap                 v3.2.3   A Laravel Nova tiptap editor field.
mockery/mockery                    1.6.7    Mockery is a simple yet flexible PHP mock object framework
monolog/monolog                    3.5.0    Sends your logs to files, sockets, inboxes, databases and various web services
myclabs/deep-copy                  1.11.1   Create deep copies (clones) of your objects
naif/toggle-switch-field           1.1.2    A Toggle Switch Field for Nova 4.
nesbot/carbon                      2.72.2   An API extension for DateTime that supports 281 different languages.
nette/schema                       v1.3.0   📐 Nette Schema: validating data structures against a given Schema.
nette/utils                        v4.0.4   🛠  Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or stron...
nikic/php-parser                   v5.0.0   A PHP parser written in PHP
nunomaduro/collision               v7.10.0  Cli error handling for console/command-line PHP applications.
nunomaduro/termwind                v1.15.1  Its like Tailwind CSS, but for the console.
openspout/openspout                v4.23.0  PHP Library to read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way
phar-io/manifest                   2.0.3    Component for reading phar.io manifest information from a PHP Archive (PHAR)
phar-io/version                    3.2.1    Library for handling version information and constraints
phpoption/phpoption                1.9.2    Option Type for PHP
phpunit/php-code-coverage          10.1.11  Library that provides collection, processing, and rendering functionality for PHP code coverage information.
phpunit/php-file-iterator          4.1.0    FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-invoker                4.0.0    Invoke callables with a timeout
phpunit/php-text-template          3.0.1    Simple template engine.
phpunit/php-timer                  6.0.0    Utility class for timing
phpunit/phpunit                    10.5.9   The PHP Unit Testing framework.
psr/cache                          3.0.0    Common interface for caching libraries
psr/clock                          1.0.0    Common interface for reading the clock.
psr/container                      2.0.2    Common Container Interface (PHP FIG PSR-11)
psr/event-dispatcher               1.0.0    Standard interfaces for event handling.
psr/http-client                    1.0.3    Common interface for HTTP clients
psr/http-factory                   1.0.2    Common interfaces for PSR-7 HTTP message factories
psr/http-message                   2.0      Common interface for HTTP messages
psr/log                            3.0.0    Common interface for logging libraries
psr/simple-cache                   3.0.0    Common interfaces for simple caching
psy/psysh                          v0.12.0  An interactive shell for modern PHP.
ralouphie/getallheaders            3.0.3    A polyfill for getallheaders.
ramsey/collection                  2.0.0    A PHP library for representing and manipulating collections.
ramsey/uuid                        4.7.5    A PHP library for generating and working with universally unique identifiers (UUIDs).
rap2hpoutre/fast-excel             v5.3.0   Fast Excel import/export for Laravel
sebastian/cli-parser               2.0.0    Library for parsing CLI options
sebastian/code-unit                2.0.0    Collection of value objects that represent the PHP code units
sebastian/code-unit-reverse-lookup 3.0.0    Looks up which function or method a line of code belongs to
sebastian/comparator               5.0.1    Provides the functionality to compare PHP values for equality
sebastian/complexity               3.2.0    Library for calculating the complexity of PHP code units
sebastian/diff                     5.1.0    Diff implementation
sebastian/environment              6.0.1    Provides functionality to handle HHVM/PHP environments
sebastian/exporter                 5.1.1    Provides the functionality to export PHP variables for visualization
sebastian/global-state             6.0.1    Snapshotting of global state
sebastian/lines-of-code            2.0.2    Library for counting the lines of code in PHP source code
sebastian/object-enumerator        5.0.0    Traverses array structures and object graphs to enumerate all referenced objects
sebastian/object-reflector         3.0.0    Allows reflection of object attributes, including inherited and non-public ones
sebastian/recursion-context        5.0.0    Provides functionality to recursively process PHP variables
sebastian/type                     4.0.0    Collection of value objects that represent the types of the PHP type system
sebastian/version                  4.0.1    Library that helps with managing the version number of Git-hosted PHP projects
spatie/backtrace                   1.5.3    A better backtrace
spatie/flare-client-php            1.4.3    Send PHP errors to Flare
spatie/ignition                    1.12.0   A beautiful error page for PHP applications.
spatie/image                       2.2.7    Manipulate images with an expressive API
spatie/image-optimizer             1.7.2    Easily optimize images using PHP
spatie/laravel-ignition            2.4.1    A beautiful error page for Laravel applications.
spatie/laravel-medialibrary        10.15.0  Associate files with Eloquent models
spatie/once                        3.1.0    A magic memoization function
spatie/temporary-directory         2.2.1    Easily create, use and destroy temporary directories
symfony/console                    v6.4.2   Eases the creation of beautiful and testable command line interfaces
symfony/css-selector               v7.0.0   Converts CSS selectors to XPath expressions
symfony/deprecation-contracts      v3.4.0   A generic function and convention to trigger deprecation notices
symfony/error-handler              v6.4.0   Provides tools to manage errors and ease debugging PHP code
symfony/event-dispatcher           v7.0.2   Provides tools that allow your application components to communicate with each other by dispatching events and listening to them
symfony/event-dispatcher-contracts v3.4.0   Generic abstractions related to dispatching event
symfony/finder                     v6.4.0   Finds files and directories via an intuitive fluent interface
symfony/http-foundation            v6.4.2   Defines an object-oriented layer for the HTTP specification
symfony/http-kernel                v6.4.2   Provides a structured process for converting a Request into a Response
symfony/mailer                     v6.4.2   Helps sending emails
symfony/mime                       v6.4.0   Allows manipulating MIME messages
symfony/polyfill-ctype             v1.28.0  Symfony polyfill for ctype functions
symfony/polyfill-intl-grapheme     v1.28.0  Symfony polyfill for intl's grapheme_* functions
symfony/polyfill-intl-icu          v1.28.0  Symfony polyfill for intl's ICU-related data and classes
symfony/polyfill-intl-idn          v1.28.0  Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions
symfony/polyfill-intl-normalizer   v1.28.0  Symfony polyfill for intl's Normalizer class and related functions
symfony/polyfill-mbstring          v1.28.0  Symfony polyfill for the Mbstring extension
symfony/polyfill-php72             v1.28.0  Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions
symfony/polyfill-php80             v1.28.0  Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions
symfony/polyfill-php83             v1.28.0  Symfony polyfill backporting some PHP 8.3+ features to lower PHP versions
symfony/polyfill-uuid              v1.28.0  Symfony polyfill for uuid functions
symfony/process                    v6.4.2   Executes commands in sub-processes
symfony/routing                    v6.4.2   Maps an HTTP request to a set of configuration variables
symfony/service-contracts          v3.4.1   Generic abstractions related to writing services
symfony/string                     v7.0.2   Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way
symfony/translation                v6.4.2   Provides tools to internationalize your application
symfony/translation-contracts      v3.4.1   Generic abstractions related to translation
symfony/uid                        v6.4.0   Provides an object-oriented API to generate and represent UIDs
symfony/var-dumper                 v6.4.2   Provides mechanisms for walking through any arbitrary PHP variable
symfony/yaml                       v7.0.0   Loads and dumps YAML files
theseer/tokenizer                  1.2.2    A small library for converting tokenized PHP source code into XML and potentially other formats
tijsverkoyen/css-to-inline-styles  v2.2.7   CssToInlineStyles is a class that enables you to convert HTML-pages/files into HTML-pages/files with inline styles. This is very useful when you...
vlucas/phpdotenv                   v5.6.0   Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.
voku/portable-ascii                2.0.1    Portable ASCII library - performance optimized (ascii) string functions for php.
webmozart/assert                   1.11.0   Assertions to validate method input/output with nice error messages.
naifalshaye commented 7 months ago

It's been tested with the same laravel and nova version. What about the Database ?

ekazda commented 7 months ago

I just realized I missed that and updated my comment above. Regardless...

MySQL 8.1.0 PHP 8.3.1

naifalshaye commented 7 months ago

Tested now on fresh install of Laravel and Nova same versions.

Screenshot 2024-01-26 at 2 35 45 AM Screenshot 2024-01-26 at 2 43 46 AM Screenshot 2024-01-26 at 2 45 01 AM Screenshot 2024-01-26 at 2 45 09 AM
ekazda commented 6 months ago

I think I figured out what is wrong with this component. It is expecting "1" or "0" as a string, not an actual boolean or number.

In my code, I have my table values properly cast so that I can do boolean operations with them. I'm doing that by setting them in my model.

boolean

I don't think this component support actual boolean values cast as boolean values... just string versions of boolean values.

I tested this with the following code...

ToggleSwitchField::make('Subscribe To Emails', 'newsletter')
    ->resolveUsing(function ($value, $resource) {
        return true;
    }),

This does NOT toggle the slider.

However, this does:

ToggleSwitchField::make('Subscribe To Emails', 'newsletter')
    ->resolveUsing(function ($value, $resource) {
        return "1";
    }),

Additionally, so does this:

ToggleSwitchField::make('Subscribe To Emails', 'newsletter')
    ->resolveUsing(function ($value) {
        return $value ? '1' : '0';
    }),

It would seem to me that this field should accept actual boolean values, as well as return them to the database properly.

ekazda commented 6 months ago

Was just curious to follow up on this and see if you were able to test the points I made above.

naifalshaye commented 6 months ago

Done, Please try now.

ekazda commented 6 months ago

Yes, this appears to have fixed the issue. Thanks for the great plugin and the support!

naifalshaye commented 6 months ago

Glad it's been fixed. Thanks for submitting the issue and the support 👍

OliverEberlei commented 5 months ago

It seems the issue still persists for me on the Index view. The Edit view works fine but the index view always shows "false" for me when $casts is setup to boolean for the property. I can still click the toggle on the index field and it correctly toggles the value in the background, it just starts of in the wrong state (it's off, when the field returns true from the database)

It does work correctly when I remove the field from my $casts variable.