Code Monkey home page Code Monkey logo

belongs-to-many-field-nova's Introduction

Hi I'm Benjamin 👋

Senior software engineer and web enthusiast with technical leading experience, worked with Laravel, Typescript, Javascript, React, Vue, Python. I love innovation and problem solving.

I love to share knowledge with the developer's community. You can find an amazing tool for laravel nova (https://github.com/Benjacho/belongs-to-many-field-nova)

Also, I participated as a speaker at Open Source Events.

  • 👨🏽‍🏫 I'm currently working on Lemontech, promoting a modern legal world.
  • 🌱 I'm currently involved in Full Stack development, data science, and a little bit of devops
  • 👨🏽‍💻 Working with **Laravel, PHP, Javascript, Python, Typescript, AWS services.
  • 📫 Reach me on Twitter.
  • 😄 Pronouns: he/him.
  • 🧱 Fun fact: I like football and videogames.

belongs-to-many-field-nova's People

Contributors

abr4xas avatar alafrance1999 avatar angelsk avatar athlon1600 avatar benjacho avatar bnoordsij avatar danieleugoletti avatar dependabot[bot] avatar dormadekhin avatar ericphamhoang avatar infostreams avatar makkinga avatar maxkorlaar avatar semihkeskindev avatar smskin avatar vhcraig 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

belongs-to-many-field-nova's Issues

Method Illuminate\Validation\Validator::validateRequird does not exist, when using BelongsToMany field.

Method Illuminate\Validation\Validator::validateRequird does not exist, when using BelongsToMany field to post data on Laravel Nova.

Code

     */
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
            Text::make('Name','name')->rules('required'),
            Image::make('Icon', 'icon')->rules('required')->disableDownload(),
            Textarea::make('Description', 'description')->rules('required'),
            Select::make('Type','type')->options([
                'Product' => 'Product',
                'Marketing' => 'Marketing',
                'Technology' => 'Technology'
            ])
            ->rules('required'),
            Textarea::make('Search tags', 'search_tags')->rules('required'),
            Select::make('Status','status')->options([
               'Active' => 'Active',
               'Achieved' => 'Achieved'
            ])
            ->rules('required'),
            BelongsTo::make('Organization', 'organization', 'App\Nova\Organization')

        ];
    }

Payload

brand: 1
brand_trashed: false
name: Succesion Vacation
description: Sveiki, ptrasjk
search_tags: kjbnnmjjkllk
priority: 6
time_frame: Next 3 Months
success_measure: Beverages Sold
objective_user: [{"id":1,"name":"Admin","value":1}]
review_date: 2020-07-21
status: Active

I assume, that I on objective_user I should pass some value not an object. Any ideas?

Rules required not working?

Hi, please see the code below. The rules required is not working?
Please help, thanks.

BelongsToManyField::make('Main Categories', 'mainCategories', 'App\Nova\MainCategory') ->options(\App\Models\MainCategory::get(['id', 'name'])) ->relationModel(\App\Models\MainCategory::class)->rules('required'),

Utilizar información en evento created

Al agregar este field en una relación y utilizar un observer de la clase asociada en el evento created solo llega un array vacío de la relación.
Tengo la clase User y una clase Product que tienes una relación de muchos a muchos.
Al crear un nuevo User agregando el field de BelongsToMany con Product, en el evento created recibo solo un array vacío de products. Las tables y la relación se crea correctamente pero necesito ejecutar un evento cuando se crea un nuevo User utilizando los Product que le corresponden al user.

Alguna sugerencia?

Missing validation error message

Hi,

I updated my Laravel from 6->8 and Nova from 2->3 and now the validation messages for BelongsToManyField has disappeared. Nova still shows the message: "There was a problem submitting the form" and the correct response data:

{
  "message":"The given data was invalid.",
  "errors":{
    "end_user":["The End user field is required."],
    "countries":["The countries field is required."]
  }
}

Skärmavbild 2021-01-13 kl  14 04 22

BelongsToManyField::make('Countries', 'countries', Country::class)
    ->rules('required'),

Select all options

Is there any way to select all the options available in one click? (like a checkbox)
In case there are many many options so the user doesn't have to select one by one if they plan to select all

Closure for the option method

Hello,

Would it be possible to add the possibility for the ->options method to take a closure as argument?

->options(function() {
    \App\Role::all()
})

When doing like this ->options(\App\Role::all()) the field generates one query per row.

Do you think it would be possible to cache it by using a closure?

//Tim

Add suppport for resolveUsing() and displayUsing() functions

Hello, congratulations on this useful package.

I am trying to manipulate the labels that the edit view shows. How can I do it?
edit

I already managed to customize the list that shows my elements. but I can't customize the objects in the edit view.

pillbox

pillbox2

While updating data if i change fleet type option and then selected parent category option which is not belongs to fleet type then also can save data without any error. It should not allow to save or if i change fleet type then selected parent category should remove so can select other options which is related to that fleet type.

What is the solution of this issue? While we change parent option it should remove the child selected options which is not related to parent. And if we save it with different parent and child options which are not belongs to each other data is saved.

I have to clear child selected data from options when we change parent options. What is the solution of this?

        BelongsTo::make('Fleet Type', 'fleetType', FleetType::class)
        ->default(function ($request) {
            if ($request->editMode == 'create') {
                return  self::MEDICAL_FLEET;
            }
        })->withMeta([
            'placeholder' => 'Select Fleet Type',
        ]),

        BelongsToManyField::make(__('Parent Category'), 'parent', Category::class)
        ->dependsOn('fleetType', 'fleet_type_id')
        ->setMultiselectProps([
            'selectLabel' => 'click for select',
            'placeholder' => 'Select Parent Category',
            'openDirection' => 'below',
            'max' => 1
        ])
        ->rules('required'),

What could be the solution that if i select other option of fleet type then selected option of parent category which is not related to that fleet type should remove. So i can select that category which is belongs to fleet type.

Help is not shown

I specified a ->help() text for the field. But it is not shown for this field type.

Error when updating

BelongsToManyField::make('Services', 'services', 'App\Nova\Service')
  ->rules('min:1','max:1','required')
  ->options(\App\Service::whereHas('counties', function ($q) 
    {
      $q->where('county_id', $this->county_id);
    }
)->get())

When I create a resource, the field correctly creates the relationships, however when I attempt to edit and update a resource it appears that Nova is trying to set a value on a column rather than sync the attached relationships:

Error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column services in 'field list' (SQL: update notes set has_notes = 0, services = ?, notes.updated_at = 2019-10-22 21:40:12 where id = 557)"

Soporte para nova 2.0

Por algún motivo el paquete lanza un error:

Argument 3 passed to Laravel\Nova\Fields\Field::__construct() must be callable or null, string given, called in /mnt/c/Users/ianto/Code/despachosv2/nova/src/Element.php on line 46

Por lo que infiero que se debe a que no soporta la versión 2.0 de nova.

Updating a model empties my BelongsToMany field

I believe this is a recent thing but when I first create a new nova resource and select my relations, they are just fine and dandy.

However, if I make another edit to the resource, when I save, my BelongsToMany relationship vanishes.

Defined as so:

BelongsToManyField::make('Authors', 'authors', 'App\Nova\Author')
                ->optionsLabel('full_name')
                ->rules('required')
                ->help('Who is featured in this video?'),

If I reassign the authors again, that works too.

How to use with spatie/translate

 $financeArray = [];
        foreach (\App\Model\FinanceType::all() as $entityType) {
            $type = new \stdClass();
            $type->id = $entityType->id;
            $type->name = $entityType->name;
            $financeArray[] = $type;
        }
            BelongsToManyField::make('AdvertFinance', 'finance', 'App\Nova\AdvertFinance')->options($financeArray),

All ok on create, but in update i see like this
image
How to resolve this?!

[BUG] Link always visible

Hi there. Great package!

A thing I've noticed is that if I have a policy for the related resource with the view() and/or viewAny(), methods set to false, the link is still visible, thus causing a 403 error when clicking on it. To keep consistency with Laravel Nova, the links should be removed and only displaying the text like the framework does.

Can you confirm this is a general bug in the package @Benjacho?

When a BelongsToManyField 'depends on' another field, if the parent field is updated, the values unmatch.

image

BelongsToManyField::make('Questions','questions', 'App\Nova\Question')
->optionsLabel('title')
->showOnUpdating(true)
->dependsOn('class_subject','class_subject_id')

Note that the objects in the BelongsToManyField get filtered based on the value in the field above it.
When I update my parent field (in this case Class Subject) to something else, it is allowing me to save the updations even though the selected objects in the BelongsToManyField don't match the parent field anymore (Class Subject).

Is it possible to clear the selected objects in the BelongsToManyField if the parent field is updated?

Error on "optional" field.

hi @Benjacho. This is a great package for nova.

I wonder if this is supposed to happen. not sure but the if I save a product and dont select the belongstomany field It throws this error. this field is optional for me. does it have to have data?

image

attaching values to every other saved object in boot()

When i try to update other objects in the boot() of the model, the package attaches the values to all the other objects that was updated too.
What i mean

protected static function boot()
{
    parent::boot();
    static::creating(function($newModel) {
       $someOtherObject = self::where('something', $newModel->something)->first();
       $someOtherObject->update(['something' => 'something-else']);
    });
}

in this case, the selected values will be attached to $someOtherObject too, not only to the newly created one.

Support JSON columns (spatie/laravel-translatable)

Need support for translations based on JSON serialization, for example when the title column is JSON output is:

{ "en": "", "lt": "Odontologija", "ru": "" }{ "en": "", "lt": "Periodontologija", "ru": "" }{ "en": "", "lt": "Implantacija", "ru": "" }

Should be something like this:

->optionsLabel('title.en')

As a temporary solution, I made a custom setter in the model.

identificador con nombre diferente

Hola Te expongo mi caso
tengo la tabla user y la tabla de turnos, por mala oganizacion los id's tiene nombres diferentes.
user ( id), turno(id_turnos) la relacion usuario_turnos(id_usuario, id_turno) .

lo que detecte es que se esta esperando siempre el campo 'id'
$values = array_column(json_decode($request->$attribute, true),'id');
por lo que no me permite insertar los valores.

la solucion que encontre fue agregar un nuevo atributo
public $attributeId = 'id';
y una nueva función
public function setAttributeId($attributeId='id'){ $this->attributeId= $attributeId; return $this; }
y modificar esta linea para que quede de esta manera
$values = array_column(json_decode($request->$attribute, true),$this->attributeId);

me parece genial tu trabajo, saludos espero sea de utilidad y si hay otra manera diferente de resolver el detalle , me gustaría saber

Saludos Cordiales.

Soporte para Pivot

Hola Benjamín

Muchas gracias por desarrollar el paquete, te quería consultar si tienes alguna idea de como manejar los datos que vienen en los pivot?

relation route return 401 unauthorized

Hi
I followed the instrctions in the readme to install and configure the package but i am unable to make it work.
The route for fetching the select data is returning a 401 unauthorized i don't know why. Here is the screenshot of the error:
image

Here is my code for implementing the plugin in nova:
BelongsToManyField::make('the Apps','appTypes', AppTypeResourceNova::class)->optionsLabel('id'),
Do you guys have an idea why this is returning 401 ?
Thanks

Multiple instances

Is there a way to use multiple instances of this field in one resource? Am I missing something?

pivot create and update

im creating a pivot for material usage

public function usages() : BelongsToMany
    {
        return $this->belongsToMany(MaterialUsage::class, 'materials_usages', 'material_id', 'material_usage_id');
    }

when i add it the created_at and updated_at is null.
how to add the datetime?

--add
how to show it on detail?

Rules are not respected

Hi guys,

I have this code:
BelongsToManyField::make('Values', 'values', 'App\Nova\Value')->rules('required', 'min:1', 'max:5', 'size:3'),

Still i can attach more than 5 values, also, the "required" property is not respected. Am I missing something here?

Depends on return only ids

BelongsTo::make('University', 'university', 'App\Nova\University'),
BelongsToManyField::make('University Campus', 'UniversityCourse', Campus::class)
->dependsOn('university', 'university_id')
->optionsLabel('name_en')
->setMultiselectProps([
'selectLabel' => 'click for select',
'closeOnSelect' => false,
])
->canSelectAll('Select All'),

            After select the university, response like this

Screenshot from 2021-03-21 15-22-26

The result in university campuses like this
Screenshot from 2021-03-21 15-24-26

How can I return the name_en instead of ids?

Create button and attach form for Belongstomany relationship

Hi there !
I'm searching a fix for our Nova App. I have a relationship belongstomany between Minute and Stakeholder in which I have a pivot.
I would love to have attach or create belongstomany relationship as shown in my screenshots :

  1. A searching field to attach stakeholders to my minute
    attach-stakeholder
  2. A create button to create new stakeholder with a modal window
    create-stakeholder
    As we have for for one level deep relationship (belongsto)
    We already found this following resources but they are not satisfaying for our users :
    https://github.com/dillingham/nova-attach-many (because we have to many resources to list and we can only attach not create)
    https://novapackages.com/packages/yassi/nova-nested-form (we can only create not attach)
    https://novapackages.com/packages/benjacho/belongs-to-many-field (we can only attach)
    Would you be available to develop this feature ? If yes what could be your expectation ?

Translatable Fields

I have an issue where I am trying to attach multiple records where the 'name' for each record is a translatable field (I'm using spatie/laravel-translatable).

When the records are displayed, the json for the fields is being displayed, not the translated names.

Create new relationship

Really hoping to get this done so lets say you are searching and no results come up, it would be really nice for a "create" button that would create the relationship instance. That way instead of having to go to another resource and creating it for it to be available all right there would really be a super helpful option.

Filter by field?

What I'm trying to achieve is to specify a list of options only when certain criteria on the database record are met. For example, for a table of users has a many-to-many relationship to countries;

CREATE TABLE `countries` (
  `id` bigint(20) unsigned,
  `name` varchar,
  `iso_code` varchar,
  `active` tinyint(1),
)

CREATE TABLE `countries_users` (
  `id` bigint(20) unsigned,
  `country_id` bigint(20) unsigned,
  `user_id` int(10) unsigned,
)

I want to filter to only show countries which have an active value of 1 (true).

Is something like this achievable?

            BelongsToManyField::make('Operating Countries', 'countries', \App\Nova\Country::class)
                ->filter(function($query) {
                   return $query->where('active', '=', true);
                })

If this is an unsupported feature, it would be useful for me to add this to this repo - if it would be of value.

Add "searchable" behavior

Hello,
First, thank you. It is a very useful nova module.

For very long lists of options, is it possible to add a "searchable" behavior which relaunches the ajax request when we change the search query.

By doing so, we can limit the results using relatableQuery and inspecting the request parameters.

Best regards.

Bug with direct Class access

Hey I have a Room model and resource. It has a column value of "name"

The way I'm calling the code actually doesnt use the "name" column but the "title()" set on the room resource:

    public function title(): string
    {
        return $this->model()->property->name . ': ' . $this->model()->name;
    }

This code below was working fine for me until I updated:

BelongsToManyField::make('Rooms', 'rooms', Room::class),

However on the latest update I now have to do the following:

BelongsToManyField::make('Rooms', 'rooms', Room::class)->optionsLabel('name'),

Weirdly its still using the title() method to display the label.. (which is good for me) but without the options label it just spits an error out (its trying to assign the string (label) rather than id on save).

I'm using 1.9 .. previously was 1.8 I believe

not work with globalScopes

Hi all
i tried to make scope in model to get some rows not all but the list in this filed show all record
Please How can I show in the list the rows which want

public static function boot(){
        parent::boot();
        static::addGlobalScope(new WhereFiledValueScope('service_type','delivering'));
}

here WhereFiledValueScope

class WhereFiledValueScope implements Scope
{
    protected $filed;
    protected $value;

    /**
     * WhereInArrayScope constructor.
     *
     * @param $filed
     * @param $value
     */
    public function __construct($filed,$value){
        $this->filed = $filed;
        $this->value = $value;
    }

    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  Builder  $builder
     * @param  Model  $model
     *
     * @return $this|Builder
     */
    public function apply(Builder $builder,Model $model){
        $bilder = $builder->where($this->filed,$this->value);
        return $bilder;
    }
}

this image show what i want
servicesTypes

Issue with optionsLabel in detailed view

With passing optionsLabel its working in add and update, because their the below code writen

this.optionsLabel = this.field.optionsLabel ? this.field.optionsLabel : 'name';

But in detailed view Means DetailField.vue file directly written
{{resource.name}}

Because of the above line while i am passing optionsLabel its showing empty

Doesn't show pickable options

  • Laravel Version: 8.34.0
  • Nova Version: 3.22.0
  • PHP Version: 7.4.16
  • MacOS, Docker, Postgres
  • Local env

Description:

I've tried several 3rd party custom fields for many-to-many management, while viewing and deleting relations work, XHR requests to their respective URLs always return full HTML document instead of data. I'm starting to think, something is wrong with my system, but don't know where to look.

Detailed steps to reproduce the issue on a fresh Nova installation:

A basic working many-to-many relation with pivot table. Nova's BelongsToMany field works as expected.

Tested with these packages:

Screenshot 2021-03-25 at 08 58 13

Browser console shows full HTML document instead of data.

Screenshot 2021-03-25 at 08 59 08

Logging from custom fields controllers doesn't help — looks like the request never gets there (works from fields' boot).

Screenshot 2021-03-25 at 09 00 45

Guidance is much appreciated.

No Error Message Visible

Hi @Benjacho ,

We are using belongs-to-many-field version 1.7, and even the error is coming in the response of the service it is not being shown in the component. Here is an screenshot of the issue:

Screenshot from 2020-06-04 20-27-04

Is this an bug of this version?
Thanks,
E.

IndexField.vue Link not absolute

The Link which is generated in the IndexField.vue is not absolute, this causes problems if you link it into another resource.

For Example i have

/admin/resources/usages/1 <-- See Screenshot

If i click on a usage listet in the table, i get the url /admin/resources/usages/usages/2 which ends up in an 404.

Bildschirmfoto 2019-10-31 um 08 40 25

Can you somehow fix that?

How can I specify the pivot table name?

I want to specify the pivot table name. by default it filters from the field table.
Is there a way to set the pivot table name through setPivot() method?

For example:

 BelongsTo::make('Association', 'association', 'App\Nova\Association'),

 BelongsToManyField::make('Participants', 'participant', 'App\Nova\Participant')
     ->dependsOn('association', 'association_id'),

It tries to search for association_id column in the participant table. Shouldn't it try to search for that column in assocation_participant table?

Use as single select

With the new option to set pivot attribtues we have a nice possibility to use this field as a single select by using
setMutliselectProps with multiple => false.

Unfortunately the field then saves nothing as Vue-Multiselect returns no array but the single selected object.
Any Idea how this could be achieved is highly appreciated.

Press enter to create tag doesn't work

Hi there, I'm using this package to select one or many categories but also I want to create a new one if doesn't exist but this doesn't work:

image

This is my config:

code

Problem to insert foreign values to pivot tables

Ok, I solved this silly issue because of my own fault.
But now I get this errors when trying to insert foreign values to pivot tables. Second error I get when I modified foreign column to plural form. P.S. This both errors I get in mentioned pivot tables.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'assets_id' in 'where clause' (SQL: select * from `assets_technical_users` where `assets_id` = 5)
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (request_mapper.objectives_users, CONSTRAINT objectives_users_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE) (SQL: insert into objectives_users (objectives_id, user_id) values (1, 15))

Source code

use Illuminate\Http\Request;
use Laravel\Nova\Fields\ID;
use Benjacho\BelongsToManyField\BelongsToManyField;
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Fields\Select;
use Laravel\Nova\Fields\Number;
use Laravel\Nova\Fields\Date;
use Spatie\TagsField\Tags;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\Textarea;


 public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),

            BelongsTo::make('Brand', 'brand', 'App\Nova\Brand'),
            Text::make('Name', 'name')->rules('required'),

            Textarea::make('Statement', 'statement')->rules('required'),

            Textarea::make('Search tags', 'search_tags')->rules('required'),

            Number::make('Priority', 'priority')->min(1)->max(10)->rules('required'),
            Select::make('Time frame', 'time_frame')->options([
                'Next Month' => 'Next Month',
                'Next 3 Months' => 'Next 3 Months',
                'Next 6 Months' => 'Next 6 Months',
                'Next 12 Months' => 'Next 12 Months',
            ])->rules('required'),
            Select::make('Successive meassure', 'success_measure')->options([
                'New Unique Visitors' => 'New Unique Visitors',
                'Beverages Sold' => 'Beverages Sold',
                'New Unique Customers' => 'New Unique Customers',
            ])->rules('required'),
            BelongsToManyField::make('Objective Owner', 'users', 'App\Nova\User')->relationModel(\App\Objectives::class)->rules('required'),
            Date::make('Review date', 'review_date')->rules('required'),
            Select::make('Status', 'status')->options([
                'Proposed' => 'Proposed',
                'Active' => 'Active',
                'Achieved' => 'Achieved'
            ])->rules('required'),


        ];
    }

getHelpText does not exist

Hi,

Since the package update to v1.9 a bug is introduced.

When trying to edit a nova resource, the following error appears
Method Benjacho\BelongsToManyField\BelongsToManyField::getHelpText does not exist. {"userId":1,"exception":"[object] (BadMethodCallException(code: 0): Method Benjacho\\BelongsToManyField\\BelongsToManyField::getHelpText does not exist.

Downgrading to v1.8 does temp fix it

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.