Coder Social home page Coder Social logo

dcasia / conditional-container Goto Github PK

View Code? Open in Web Editor NEW
115.0 6.0 37.0 513 KB

Provides an easy way to conditionally show and hide fields in your Nova resources.

License: MIT License

Vue 31.59% JavaScript 0.77% PHP 67.64%
laravel nova dependency conditional laravel-nova-field conditional-field

conditional-container's Introduction

Conditional Container

Latest Version on Packagist Total Downloads License

Laravel Nova Conditional Container in action

Provides an easy way to conditionally show and hide fields in your Nova resources.

Installation

You can install the package via composer:

composer require digital-creative/conditional-container

Usage

Basic demo showing the power of this field:

use DigitalCreative\ConditionalContainer\ConditionalContainer;
use DigitalCreative\ConditionalContainer\HasConditionalContainer;

class ExampleNovaResource extends Resource {

    use HasConditionalContainer; // Important!!

    public function fields(Request $request)
    {
        return [
    
            Select::make('Option', 'option')
                  ->options([
                      1 => 'Option 1',
                      2 => 'Option 2',
                      3 => 'Option 3',
                  ]),
    
            Text::make('Content', 'content')->rules('required'),
    
            /**
             * Only show field Text::make('Field A') if the value of option is equals 1
             */
            ConditionalContainer::make([ Text::make('Field A') ])
                                ->if('option = 1'),
    
            /**
             * Equivalent to: if($option === 2 && $content === 'hello world')
             */
            ConditionalContainer::make([ Text::make('Field B') ])
                                ->if('option = 2 AND content = "hello world"'),
    
            /**
             * Equivalent to: if(($option !== 2 && $content > 10) || $option === 3)
             */
            ConditionalContainer::make([ Text::make('Field C')->rules('required') ])
                                ->if('(option != 2 AND content > 10) OR option = 3'),
           
            /**
             * Example with Validation and nested ConditionalContainer!
             * Equivalent to: if($option === 3 || $content === 'demo')
             */
            ConditionalContainer::make([

                                    Text::make('Field D')->rules('required') // Yeah! validation works flawlessly!!
                                
                                    ConditionalContainer::make([ Text::make('Field E') ])
                                                        ->if('field_d = Nice!')
                                
                                ])
                                ->if('option = 3 OR content = demo')
        ];
    }

}

The ->if() method takes a single expression argument that follows this format:

(attribute COMPARATOR value) OPERATOR ...so on

you can build any complex logical operation by wrapping your condition in () examples:

ConditionalContainer::make(...)->if('first_name = John');
ConditionalContainer::make(...)->if('(first_name = John AND last_name = Doe) OR (first_name = foo AND NOT last_name = bar)');
ConditionalContainer::make(...)->if('first_name = John AND last_name = Doe');

you can chain multiple ->if() together to group your expressions by concern, example:

ConditionalContainer::make(...)
                    //->useAndOperator()
                    ->if('age > 18 AND gender = male')
                    ->if('A contains "some word"')
                    ->if('B contains "another word"');

by default the operation applied on each ->if() will be OR, therefore if any of the if methods evaluates to true the whole operation will be considered truthy, if you want to execute an AND operation instead append ->useAndOperator() to the chain

Currently supported operators:

  • AND
  • OR
  • NOT
  • XOR
  • and parentheses

Currently supported comparators:

Comparator Description
> Greater than
< Less than
<= Less than or equal to
>= Greater than or equal to
== Equal
=== Identical
!= Not equal
!== Not Identical
truthy / boolean Validate against truthy values
contains / includes Check if input contains certain value
startsWith Check if input starts with certain value
endsWith Check if input ends with certain value

Examples

  • Display field only if user has selected file
[
    Image::make('Image'),
    ConditionalContainer::make([ Text::make('caption')->rules('required') ])
                        ->if('image truthy true'),
]
  • Display extra fields only if selected morph relation is of type Image or Video
[
    MorphTo::make('Resource Type', 'fileable')->types([
        App\Nova\Image::class,
        App\Nova\Video::class,
        App\Nova\File::class,
    ]),
    
    ConditionalContainer::make([ Image::make('thumbnail')->rules('required') ])
                        ->if(function () {
                            return 'fileable = ' . App\Nova\Image::uriKey();
                        })
                        ->if(function () {
                            return 'fileable = ' . App\Nova\Video::uriKey();
                        })
]
  • Display inline HTML only if Reason field is empty, show extra fields otherwise.
[
    Trix::make('Reason'),
    
    ConditionalContainer::make([ Text::make('Extra Information')->rules('required') ])
                        ->if('reason truthy true'),
    
    ConditionalContainer::make([
                            Heading::make('<p class="text-danger">Please write a good reason...</p>')->asHtml()
                        ])
                        ->if('reason truthy false'),
]

License

The MIT License (MIT). Please see License File for more information.

conditional-container's People

Contributors

bolechen avatar dnwjn avatar dormadekhin avatar israel5 avatar kayacekovic avatar mennotempelaar avatar milewski avatar nw-b avatar sjoertjuh avatar timcv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

conditional-container's Issues

TypeError: this.field.expressionsMap is undefined

I have nova version 3.16.3 and this package 1.2.2, but that doesn't seem to be working:

In my fields list:

use Benjacho\BelongsToManyField\BelongsToManyField;
use DigitalCreative\ConditionalContainer\ConditionalContainer;


ConditionalContainer::make(
                [
                    BelongsToManyField::make('Відділення', 'departments', Department::class),
                ]
            )->if('patronymic = "teacher"'),
TypeError: this.field.expressionsMap is undefined
    watchableAttributes http://localhost:8077/nova-api/scripts/conditional-container:1
    get http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    evaluate http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    yn http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    registerDependencyWatchers http://localhost:8077/nova-api/scripts/conditional-container:1
    deepSearch http://localhost:8077/nova-api/scripts/conditional-container:1
    deepSearch http://localhost:8077/nova-api/scripts/conditional-container:1
    deepSearch http://localhost:8077/nova-api/scripts/conditional-container:1
    deepSearch http://localhost:8077/nova-api/scripts/conditional-container:1
    deepSearch http://localhost:8077/nova-api/scripts/conditional-container:1
    mounted http://localhost:8077/nova-api/scripts/conditional-container:1
    It http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    en http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    insert http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    x http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    Ii http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    _update http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    mount http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    get http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    run http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    fn http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    ee http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    Gt http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    promise callback*Ut http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    ee http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    update http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    update http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    notify http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    set http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    set http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    e http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    x http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    _invoke http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    t http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    o http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    o http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    promise callback*o http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    default http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    t http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    default http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    getFields http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    e http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    x http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    _invoke http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    t http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    o http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    default http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    t http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    default http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    created http://localhost:8077/vendor/nova/app.js?id=ceb1f62e6f9ca43eed65:1
    It http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    en http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    _init http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    a http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    componentInstance http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    init http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    n http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    d http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    d http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    Ii http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    _update http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    mount http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    get http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    run http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1
    fn http://localhost:8077/vendor/nova/vendor.js?id=3810bf2033e3670b2acc:1

Trying to get property 'controller' of non-object - quick fix.

I'm using Maatwebsite/Laravel-Excel importer to import models by examining the Nova resources.

We've recently updated from L7 to L8 and updated all our packages and this line in HasConditionalContainer trait:

$controller = $request->route()->controller;

is now causing the error: "Trying to get property 'controller' of non-object"

Can we get some protection against this please with:

$controller = $request->route() ? $request->route()->controller : null;

so that I don't have to override this trait?

Thanks.

help text is not showing

Hello.

Thx for your great work!
Unfortunately I’ve found a little bug. The following code does not show the help text on the front-end:

ConditionalContainer::make([ Text::make('title') ->help(__('title-help')), ]) ->if('title = yes'),

Validation not working

  Number::make('Office', 'non_billable_doc_hours')->help('(non-billable)')->min(0)->max(1000)->step(0.25)->hideFromIndex(),
            ConditionalContainer::make([
                Text::make('Office Description', 'non_billable_doc_hours_description')->hideFromIndex()->rules('required'),
            ])->if('non_billable_doc_hours != 0'),

The intention here is that if I leave the Office field blank/zero, I can submit my form. If the "Office" field is not zero, then I show a text field and require input. Problem is, the form won't submit even if the "Office Description" is hidden, as I get a validation error stating that it's required.

Am I mistaken, or should the "Office Description" field's validation rules only kick in if the field is shown?

Can't render Panel inside container

ConditionalContainer::make(
  new Panel('This is a panel', $this->fields())
)->if('type = 1')

The above will render the fields, but not the Panel.

How to work with another packages that changes DOM too.

Hello.

Please see this issue in another package: armincms/nova-tab#1

I'm using this armincms/nova-tab and as conditional-container changes the DOM, the component tab component does not works properly, because the fields array where changed with conditional-container

Can you please tell us a way to solve this when use conditional-container alongside other components that changes DOM too?

Too few arguments to function Illuminate\Database\Eloquent\Model::setAttribute()

  • ConditionalContainer: 1.0.5
  • Laravel Version: 6.4.0
  • Nova Version: 2.5.0
  • PHP Version: 7.3.9
  • Database Driver and Version: MySQL 5.7.24 Community
  • Operating System and Version: Windows 10 64 bits
  • Browser type and version: Google Chrome 7.0.3865.90 64 bits
  • Reproduction Repository: https://github.com/wemersonrv/nova-issue-show

Description

In resource resource Cliente when editing, sometimes receive this exception:

{
    "message": "Too few arguments to function Illuminate\\Database\\Eloquent\\Model::setAttribute(), 1 passed in D:\\DadosImportantes\\dev\\Projetos\\MaisControl\\MaisContratos\\issue\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Concerns\\HasAttributes.php on line 619 and exactly 2 expected",
    "exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
    "file": "D:\\DadosImportantes\\dev\\Projetos\\MaisControl\\MaisContratos\\issue\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Concerns\\HasAttributes.php",
    "line": 567,
    "trace": [
        {
            "file": "D:\\DadosImportantes\\dev\\Projetos\\MaisControl\\MaisContratos\\issue\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Concerns\\HasAttributes.php",
            "line": 619,
            "function": "setAttribute",
            "class": "Illuminate\\Database\\Eloquent\\Model",
            "type": "->"
        },
        {
            "file": "D:\\DadosImportantes\\dev\\Projetos\\MaisControl\\MaisContratos\\issue\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Concerns\\HasAttributes.php",
            "line": 573,
            "function": "setMutatedAttributeValue",
            "class": "Illuminate\\Database\\Eloquent\\Model",
            "type": "->"
        },
        {
            "file": "D:\\DadosImportantes\\dev\\Projetos\\MaisControl\\MaisContratos\\issue\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Traits\\ForwardsCalls.php",
            "line": 23,
            "function": "setAttribute",
            "class": "Illuminate\\Database\\Eloquent\\Model",
            "type": "->"
        },
        {
            "file": "D:\\DadosImportantes\\dev\\Projetos\\MaisControl\\MaisContratos\\issue\\vendor\\laravel\\framework\\src\\Illuminate\\Http\\Resources\\DelegatesToResource.php",
            "line": 132,
            "function": "forwardCallTo",
            "class": "Laravel\\Nova\\Resource",
            "type": "->"
        },

Steps To Reproduce the Issue

  1. Add a Cliente Resource, and add a Pessoa Física Cliente.
  2. Use this site to generate a fake Brazilian CPF: https://www.4devs.com.br/gerador_de_cpf
  3. Save it and, and go to edit the same record
  4. Do not fill anything and save again.

A this point you will see the exception. But, if you add other record using Pessoa Jurídica, it works fine.

Important

After receive the error, if you go to resource Clientes OK and edit the same record and save it will works.

The resource Clientes OK a copy of Clientes resource, but created to works without ConditionanContainer but for Pessoa Física type, it has the same fields data... And to show that it works fine!

Show hidden fields on index

Hi,

Would it be possible to show hidden fields on index and give them a null value when they are missing?

/Tim

error with panel

Argument 1 passed to parseThirdPartyPackageFieldValue() must be an instance of Laravel\Nova\Fields\Field, instance of Laravel\Nova\Panel given
in fields isset panel, which contains ConditionalContainer

Validation not working

In docs there is mentioned that validation works but in my case it doesn't.

ConditionalContainer::make([
                Text::make(__('Username'), 'username')
                    ->sortable()
                    ->creationRules('required', 'unique:users,username', 'max:254', 'alpha_dash')
                    ->updateRules('sometimes', 'required', 'unique:users,username,{{resourceId}}', 'max:254', 'alpha_dash'),
            ])->if('role != 3'),

even i tried only "->rules('required')" still no luck. It is fine without ConditionalContaier. Only attributes within the container are not getting validated.

Laravel Framework 6.5.2
Nova 2.7.1

Passing a closure to if method throws an error

The MorphTo example here indicates a way to pass a closure to the if method, but doing so causes an error.

Error:

Argument 1 passed to 
App\Nova\InvoiceItem::DigitalCreative\ConditionalContainer\{closure}() 
must be of the type string, object given

BelongsToManyField still not working inside ConditionalContainer

I see the commit to support Benjacho\BelongsToManyFiel, but I'm still getting a Trying to get property 'resourceClass' of non-object error if I put it inside ConditionalContainer.

I'm using

  • Nova v3.22.0
  • conditional-container v1.3.2
  • belongs-to-many-field v1.8

Does not work with File Fields. Upon editing the Resource, the File field is reset to null.

Steps to Reproduce:

(1) Setup something like:

ConditionalContainer::make([
   File::make('Proof of Service', 'current_proof_of_service')->updateRules('file', 'mimes:pdf')
])->if('has_current_proof_of_service truthy true'),

(2) Update the form. When you go back to the detail view, observe you can see the file was uploaded.

(3) Click on Edit, and save w/out updating the file.

(4) ❗ Observe the file has been removed an is now NULL.

ConditionalContainer breaks benjaco/belongs-to-many

I'm trying to use benjacho/belongs-to-many inside a conditional container. A few issues I've found:

  1. If you use the native Nova readonly() method, the field is not disabled as it should be. The user can still interact with the input and change the value...however it appears that the field is still succesfully "read only" in the sesnse that the value does not change in the form object on submission... weird right? This ONLY happens when the field is wrapped in a ConditionalContainer.

  2. There is a weird error when trying to update a record and the belongs-to-many field is wrapped in a ConditionalContainer. It appears that the field is treated as a column rather than a pivot (belongs to many, so there's no "column" to update per-se).

Inline BelongsToMany field

Do you have any idea about how to get it working with NovaAttachMany och BelongsToManyField?

The attributeValue for NovaAttachMany is a JSON (or string, not shure) like [1,12,3]. And my problem is that for example "roles contains 1" will match both 1 and 12.

The attributeValue BelongsToManyField is an object and i cant compare to objects..

Do you have any idea how to make a field dependent on an Inline ManyToMany field with your field?

/Tim

Populate in edit mode

  1. Excellent package.
  2. If I want to enter a master password before any field is shown, the desired fields will not return their values from the database.

How can I add values as intended?
As seen in the screenshot, values are not populated.

image

Conditional Container not showing in detail view page

Hi and thanks for the great package.
I noticed that if I use a conditional container inside a panel I can't see the fields inside the container in the view page.
No problems instead in the edit page, and no problem in the view page if I put the fields outside the container.
Someone has the same problem?
Thanks.

Compatibility with panel

Hello,
is it compatible with panel field panel ?
Because I don't see the label of any panel .
thanks

Versions greater than 1.1.6 are backwards incompatible with Nova 2.x branch.

ex. updating to 1.1.7, 1.1.8 causes a hard break due to the addition of $this->fieldsMethod($request) in src/HasConditionalContainer.php

Releasing breaking changes in a patch version update is generally unexpected, should this not be in conditional-container 1.2.x or at least define nova 3.x as a dependency?

Identify string length

Hi! I'm just wondering if this package can count the string length??

->if('field->length > 0')

Like so..

Can not work with json field

Hello. In my project I use json field in mysql for store user meta data, the user model like this

...
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'meta' => 'array',
    ];

When I use nova, i can use meta field like this, it works perfect.

            Toggle::make('Have Meta', 'meta->flag'),
            Text::make('Meta Point', 'meta->point'),
            Number::make('Meta Amount', 'meta->amount'),

But when i use this package the field content is always empty to get from database.

            Toggle::make('Have Meta', 'meta->flag'),

            ConditionalContainer::make([
                Text::make('Meta Point', 'meta->point'),
                Number::make('Meta Amount', 'meta->amount'),
            ])->if('meta->flag = true'),

I take a screenshot below, the top two fields is in the ConditionalContainer call, is empty, the above two is normal nova fields.

Please help me, where am i wrong?

image

Conditional field is not being displayed inside a nested form

Hey

I have a Post model which can be of 2 types: regular and poll. A Post model of type poll will be related to a Poll model in a 1-1 manner. Among all other attributes, a Poll model has selection_mode and max_selected_count. With all of these said, here is my issue:

I'm using yassipad/laravel-nova-nested-form to display create/update form of a Poll model inside create/update form its related Post. Also, I wrap max_selection_count field of Poll inside a ConditionalContainer field to make it visible only if selection_mode is equal to multiple.

Everything works fine in isolation, but when it comes to max_selection_count field inside the Post create/update page, it does not work as expected. Inside Post form and when type is poll, no matter what option I choose for selection_mode, max_selection_count will not appear (but it works inside Poll form isolated from Post form).

Here is my code snippets:

// app/Nova/Post.php
public function fields(Request $request)
{
    return [
        // ...
        Select::make('type')->options(['Regular' => 'regular', 'Poll' => 'poll']),
        ConditionalContainer::make([
            NestedForm::make('poll', Poll::class)
        ])->if('type = poll')
    ];
}
// app/Nova/Poll.php
public function fields(Request $request)
{
    return [
        // ...
        Select::make('selection_mode')->options(['Single' => 'single', 'Multiple' => 'multiple']),
        ConditionalContainer::make([
            Number::make('max_selection_count')
        ])->if('selection_mode = multiple'),
    ];
}

BelongsTo not working inside container

Hi,

When i put a regular BelongsTo field in the ConditionalContainer i get the following error.

/vendor/laravel/nova/src/Http/Controllers/AssociatableController.php:25
"Trying to get property 'resourceClass' of non-object"

This is found on row 25 in AssociatableController.php

$withTrashed = $this->shouldIncludeTrashed(
    $request, $associatedResource = $field->resourceClass
);

The problem seemes to be that the $field value is NULL.

My code:

ConditionalContainer
    ::make([
        BelongsTo::make('End user')
            ->sortable()
            ->rules('required'),
        ])
        ->if('is_checked truthy false'),

Boolean::make('Is checked', 'is_checked')
                ->hideFromIndex(),

Do you have any ideas?

/Tim

#14 Validation related issue

Another issue related to #14
when password field is nullable, it submits password to db as null and db updates the value to null (db password field is nullable) but when i use without ConditionalContainer, null value does not update db so old password stays. Why does it updates db when field is submit empty? it should ignore the field.

Password::make(__('Password'), 'password')
                    ->onlyOnForms()
                    ->creationRules('required', 'string', 'min:8')
                    ->updateRules('sometimes', 'nullable', 'string', 'min:8')

I am not sure why but sometimes does not work. Not sure if it's Nova's bug or this package's

Adding conditional fields to a Nova resource which are NOT fields in the DB.

We have a voucher model, which has percentage and fixed discount fields.

I have a conditional dropdown to show and hide these fields using your packag e.g.

Select::make('Type', 'type')
            ->options([
                1 => 'Fixed Amount',
                2 => 'Percentage',
            ]),

However, there is no need to save this 'type' in the database.
The problem is that when we save this resource - it complains that 'type' is not a field in the database.

Is there any way to make Nova ignore certain fields like this?

Does this package support fields with existing values?

Hi, just playing with this and I'm a bit confused.

Toggling field display depending on the value of another field is working perfectly but the fields which are being conditionally displayed are not being populated with their values from the database.

Not sure if I'm doing something wrong, or if this behavior is expected? Is the package designed to be used in a create scenario but not for updates?

Also, does it work on the detail view? Clearly not dynamically but for example, if 'exported' is set to true, display some extra fields: 'export_date', etc...

Thanks

Edit page is not loading with HasConditionalContainer

I updated to Nova v3.12.0 and Conditional Container v1.2. When I did this my edit pages for the pages containing ConditionalContainer stopped loading. It only happens after I added Use HasConditionalContainer;. Without HasConditionalContainer I get the error of TypeError: this.field.expressionsMap is undefined but with it nothing shows up on the page.

It does work as expected on Create, but once I save and try to edit the item it breaks and becomes hidden with no errors that I can see.

Screen Shot 2020-10-07 at 10 53 47 PM

Froala wysiwyg Uploading Image Issue

It seems that the Conditional Container removes the fields from the Nova Fields Collections so that ->availableFields() doesn't return them. When we try to upload an image we get a 404 since the field is non existent in the data. Is there another way to field the field, and is there a reason you're removing them from the Nova Field Collection?

does not work with : fieldsForCreate, fieldsForUpdate

Hi,
As Documentation says :

Dynamic Field Methods Precedence ::
The fieldsForIndex, fieldsForDetail, fieldsForCreate, and fieldsForUpdate methods always take precedence over the fields method.
$allFields = $this->fields($request);
Many thx

MorphTo field with AND condition not working

I have a morphTo with an AND condition as shown below. I can't seem to get this to work. Can you please let me know if I am missing something?

MorphTo::make('Invoice Type', 'buyable')->types([
                Classes::class,
                Product::class,
            ]),

            ConditionalContainer::make([
                RadioButton::make('Discountable')->options([
                    'YES' => 'Yes',
                    'NO'  => 'No',
                ]),
            ])->if('(buyable = '.Classes::uriKey().' AND buyable.type = "SUBSCRIPTION")'),

Container with Boolean Field

I'm using a Boolean field (checkbox) to display extra fields when the box is checked. But I can't seem to get it to work...

Thought it would work with:

Boolean::make('Field');

ConditionalContainer::make([...])
->if('field == true')
or ->if('field truthy true')
or -> if('field boolean true')

But none of them seem to work...

When in edit mode form is not loading.

When you use the ConditionalContainer while editing a resource the edit page won't load anymore if the condition matches. If the conditions don't match the page is loading normal.

Select::make('Invoice Period', 'invoice_period')
->options(['never' => 'Never', 'ten_days'  => 'Ten days', 'monthly' => 'Monthly'])
->sortable()
->displayUsingLabels()
->rules('required'),
ConditionalContainer::make([Text::make('Description', 'description')
->hideFromIndex()])
->if('invoice_period = ten_days OR invoice_period = monthly')

So if the resource loads with invoice_period never the page will load normal if the resource loads with the invoice_period on ten_days or monthly the page won't load.

Actions

Would it be possible to make this package work in Action modals?

/Tim

availablePanelsForDetail($request) bug

Declaration of DigitalCreative\ConditionalContainer\HasConditionalContainer::availablePanelsForDetail($request) should be compatible with Laravel\Nova\Resource::availablePanelsForDetail(Laravel\Nova\Http\Requests\NovaRequest $request, Laravel\Nova\Resource $resource)

@mennotempelaar

Nova Flexible Content - Usage with Presets

I know, I am really anoying, but I still can't get it up and running on my real scenario, where I use Flexible Content Presets:

Nova Resource

public function fields() {
    return [
        Tab::make($this->title(), [
            ....
            "Content Blocks" => [
                Flexible::make('', 'gridBlocks')
                    ->preset(GridFlexibel::class)
            ]
        ])  
    ];
}

Flexible Preset

class GridFlexibel extends Preset {
    public function handle(Flexible $field) {
        $field->addLayout(HtmlLayout::class);
    }
}

Flexible HtmlLayout

public function fields() {
    return [
        Select::make("Type", "type")->options([
            "html" => "HTML",
            "plain" => "Plaintext",
        ]),
        ConditionalContainer::make([
            Trix::make('Content', 'html_content'),
        ])->if('type = html'),
        ConditionalContainer::make([
            Textarea::make('Content', 'plain_content'),
        ])->if('type = plain'),
    ];
}

And I get the

cannot read property 'join' of undefined at p.watchableAttributes

error. I tried to add the trait HasConditionalContainer to the model and to the HtmlLayoutas well, but nothing worked.

Sorry for being so anoying.

Problem on update "Unknown column 'conditional_container_xxx"

Hi. I'm having some issues when I try to update any value inside a ConditionalContainer

On create its all good and custom validation works perfect, but on updates it breaks because of

Column not found: 1054 Unknown column 'conditional_container_umis8ij2m2' in 'field list'

It fails on any Resource update:
Column not found: 1054 Unknown column 'conditional_container_n78s7zhuvv' in 'field list' (SQL: update campaign_criteria set active = 1, conditional_container_n78s7zhuvv = ?, conditional_container_69av6xtx9w = ?, conditional_container_6ankofrrcr = ?, conditional_container_pefz0rbda2 = ?, conditional_container_jlugbekiw0 = ?, conditional_container_tkhlt2gubt = ?, conditional_container_jjqnarr4jk = ?, conditional_container_nn34aros7g = ?, campaign_criteria.updated_at = 2020-05-26 18:16:11 where id = 18)

And during the insert in action_events table
insert into action_events (batch_id, user_id, name, actionable_type, actionable_id, target_type, target_id, model_type, model_id, fields, original, changes, status, exception, updated_at, created_at) values ('90a77423-e5dc-40c4-8945-df74098de0fc', 1, 'Update', 'App\Models\CampaignCriteria', 18, 'App\Models\CampaignCriteria', 18, 'App\Models\CampaignCriteria', 18, '', '{"active":1}', '{"active":true,"conditional_container_3ywtvpnayw":null,"conditional_container_nidwiv6qkk":null,"conditional_container_vnulqwmmn0":null,"conditional_container_jdj8oty4yh":null,"conditional_container_txpqr8vmqe":null,"conditional_container_8x87gkuoo8":null,"conditional_container_d10f8ut25a":null,"conditional_container_p1csk2kjhn":null}', 'finished', '', '2020-05-26 10:27:04', '2020-05-26 10:27:04')

Any idea?

Thanks!

Nova Flexible Content

Hello,

Is it compatible with Nova Flexible Content ?

I tried it and had a JS error..

Thanks !

Conditional statements referencing values within container don't work

I have a ConditionalContainer to show and hide 'advanced options' for voucher codes and when I edit the Nova resource I want to test the contents of that container and show the container if it has some values set within it.

e.g. I want the following container to show if the min_basket field has a value.

Text::make( __('Code'),  'code')
            ->rules('required')
            ->sortable()
        ,                     
        ConditionalContainer::make([
            Text::make( __('Min Basket Value'),  'min_basket')
                ->hideFromIndex()
                ->sortable()
        ])->if('min_basket truthy true')

but it doesn't work.
However, if I use the 'code' field in the if statement e.g.

Text::make( __('Code'),  'code')
            ->rules('required')
            ->sortable()
        ,                     
        ConditionalContainer::make([
            Text::make( __('Min Basket Value'),  'min_basket')
                ->hideFromIndex()
                ->sortable()
        ])->if('code truthy true')

then it does show and hide depending on the content of the field 'code'

Is this not possible to show/hide depending on fields within the container?

TypeError: Cannot read property 'join' of undefined

Thank you for this very helpful package.
I am getting 'TypeError: Cannot read property 'join' of undefined' error in all my resources. I tried all cases but no luck. I traced the error it is in FormField.vue:
watchableAttributes() { return this.field.expressionsMap.join() }

I am using:
Laravel Framework 7.4.0
Nova: v3.2.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.