GithubHelp home page GithubHelp logo

outl1ne / nova-menu-builder Goto Github PK

View Code? Open in Web Editor NEW
238.0 10.0 86.0 4.76 MB

This Laravel Nova package allows you to create and manage menus and menu items.

License: MIT License

JavaScript 4.74% Vue 41.35% PHP 53.89% CSS 0.02%
laravel-nova menu-builder menus nova managing-menus

nova-menu-builder's Introduction

Nova Menu Builder

Latest Version on Packagist Total Downloads

This Laravel Nova package allows you to create and manage menus and menu items.

Requirements

  • php: >=8.0
  • laravel/nova: ^4.0

Features

  • Menu management
  • Menu items management
    • Simple drag-and-drop nesting and re-ordering
  • Custom menu item types support
    • Ability to easily add select types
    • Ability to add custom fields
    • Use menubuilder:type command to easily create new types
  • Fully localizable

Screenshots

Menu Detail View

Menu Item Edit

Installation and Setup

Installing the package

Install the package in a Laravel Nova project via Composer, edit the configuration file and run migrations.

# Install the package
composer require outl1ne/nova-menu-builder

# Publish the configuration file and edit it to your preference
# NB! If you want custom table names, configure them before running the migrations.
php artisan vendor:publish --tag=nova-menu-builder-config

Register the tool with Nova in the tools() method of the NovaServiceProvider:

// in app/Providers/NovaServiceProvider.php

public function tools()
{
    return [
        // ...
        \Outl1ne\MenuBuilder\MenuBuilder::make(),

        // Optional customization
        ->title('Menus') // Define a new name for sidebar
        ->icon('adjustments') // Customize menu icon, supports heroicons
        ->hideMenu(false) // Hide MenuBuilder defined MenuSection.
    ];
}

Setting up

After publishing the configuration file, you have to make some required changes in the config:

# Choose table names of your liking by editing the two key/values:
'menus_table_name' => 'nova_menu_menus',
'menu_items_table_name' => 'nova_menu_menu_items',

# Define the locales for your project:
# If your project doesn't have localization, you can just leave it as it is.
# When there's just one locale, anything related to localization isn't displayed.
'locales' => ['en' => 'English'],

# Define the list of possible menus (ie 'footer', 'header', 'main-menu'):
'menus' => [
    // 'header' => [
    //     'name' => 'Header',
    //     'unique' => true,
    //     'menu_item_types' => []
    // ]
],

# If you're just setting up, this is probably of no importance to you,
# but later on, when you want custom menu item types with custom fields
# , you can register them here:
'menu_item_types' => [],

Next, just run the migrations and you're set.

# Run the automatically loaded migrations
php artisan migrate

Optionally publish migrations

This is only useful if you want to overwrite migrations and models. If you wish to use the menu builder as it comes out of the box, you don't need them.

# Publish migrations to overwrite them (optional)
php artisan vendor:publish --tag=nova-menu-builder-migrations

Usage

Locales configuration

You can define the locales for the menus in the config file, as shown below.

// in config/nova-menu.php

return [
  // ...
  'locales' => [
    'en' => 'English',
    'et' => 'Estonian',
  ],

  // or using a closure (not cacheable):

  'locales' => function() {
    return nova_lang_get_locales();
  }

  // or if you want to use a function, but still be able to cache it:

  'locales' => '\App\Configuration\NovaMenuConfiguration@getLocales',

  // or

  'locales' => 'nova_lang_get_locales',
  // ...
];

Custom menu item types

Menu builder allows you create custom menu item types with custom fields.

Create a class that extends the Outl1ne\MenuBuilder\MenuItemTypes\BaseMenuItemType class and register it in the config file.

// in config/nova-menu.php

return [
  // ...
  'menu_item_types' => [
    \App\MenuItemTypes\CustomMenuItemType::class,
  ],
  // ...
];

In the created class, overwrite the following methods:

/**
 * Get the menu link identifier that can be used to tell different custom
 * links apart (ie 'page' or 'product').
 *
 * @return string
 **/
public static function getIdentifier(): string {
    // Example usecase
    // return 'page';
    return '';
}

/**
 * Get menu link name shown in  a dropdown in CMS when selecting link type
 * ie ('Product Link').
 *
 * @return string
 **/
public static function getName(): string {
    // Example usecase
    // return 'Page Link';
    return '';
}

/**
 * Get list of options shown in a select dropdown.
 *
 * Should be a map of [key => value, ...], where key is a unique identifier
 * and value is the displayed string.
 *
 * @return array
 **/
public static function getOptions($locale): array {
    // Example usecase
    // return Page::all()->pluck('name', 'id')->toArray();
    return [];
}

/**
 * Get the subtitle value shown in CMS menu items list.
 *
 * @param $value
 * @param $data The data from item fields.
 * @param $locale
 * @return string
 **/
public static function getDisplayValue($value, ?array $data, $locale) {
    // Example usecase
    // return 'Page: ' . Page::find($value)->name;
    return $value;
}

/**
 * Get the enabled value
 *
 * @param $value
 * @param $data The data from item fields.
 * @param $locale
 * @return string
*/
public static function getEnabledValue($value, ?array $data, $locale)
{
  return true;
}

/**
 * Get the value of the link visible to the front-end.
 *
 * Can be anything. It is up to you how you will handle parsing it.
 *
 * This will only be called when using the nova_get_menu()
 * and nova_get_menus() helpers or when you call formatForAPI()
 * on the Menu model.
 *
 * @param $value The key from options list that was selected.
 * @param $data The data from item fields.
 * @param $locale
 * @return any
 */
public static function getValue($value, ?array $data, $locale)
{
    return $value;
}

/**
 * Get the fields displayed by the resource.
 *
 * @return array An array of fields.
 */
public static function getFields(): array
{
    return [];
}

/**
 * Get the rules for the resource.
 *
 * @return array A key-value map of attributes and rules.
 */
public static function getRules(): array
{
    return [];
}

/**
 * Get data of the link visible to the front-end.
 *
 * Can be anything. It is up to you how you will handle parsing it.
 *
 * This will only be called when using the nova_get_menu()
 * and nova_get_menus() helpers or when you call formatForAPI()
 * on the Menu model.
 *
 * @param null $data Field values
 * @return any
 */
public static function getData($data = null)
{
    return $data;
}

Returning the menus in a JSON API

nova_get_menus()

A helper function nova_get_menus is globally registered in this package which returns all the menus including their menu items in an API friendly format.

public function getMenus(Request $request) {
    $menusResponse = nova_get_menus();
    return response()->json($menusResponse);
}

Get single menu via identifier

// Available helpers
nova_get_menu_by_slug($menuSlug, $locale = null)
nova_get_menu_by_id($menuId, $locale = null)

To get a single menu, you can use the available helper functions.
Returns null if no menu with the identifier is found or returns the menu if it is found. If no locale is passed, the helper will automatically choose the first configured locale.

Credits

License

Nova Menu Builder is open-sourced software licensed under the MIT license.

nova-menu-builder's People

Contributors

arrowsgm avatar bastihilger avatar dependabot[bot] avatar harmenjanssen avatar hejianong avatar jimmylet avatar jordythevulder avatar kaareloun avatar kasparrosin avatar kikoseijo avatar krato avatar liorocks avatar mariuskli avatar martin-ro avatar marttinnotta avatar matislepik avatar mgralikowski avatar mohamedlbn avatar omarhen avatar pieterxjan avatar ragash avatar rdaitan-cp avatar senexis avatar sloveniangooner avatar stepanenko3 avatar stryaponoff avatar tarpsvo avatar ttungbmt avatar tyler-secretninjas avatar veezex 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  avatar  avatar  avatar  avatar

nova-menu-builder's Issues

[bug] parent_id is always null

Nova: 3.20
PHP: 7.4
DB: PostgreSQL 12
Menu: 5.2.*

When I try to set menu item as child, parent_id stays as null and never updates. Can't make a nested menu.

2021-03-05_120056

refresh page...

2021-03-05_120322

[bug] Can't install on PostgreSQL 12

Nova: 3.20
PHP: 7.4
DB: PostgreSQL 12
Menu: 5.2.*

Migrating: 2019_11_08_000000_create_menus_table
Migrated:  2019_11_08_000000_create_menus_table (65.08ms)
Migrating: 2019_11_08_000001_add_locale_parent_id_to_table
Migrated:  2019_11_08_000001_add_locale_parent_id_to_table (10.32ms)
Migrating: 2020_08_18_000001_add_data_column_to_table
Migrated:  2020_08_18_000001_add_data_column_to_table (1.50ms)
Migrating: 2020_09_15_000000_rework_locale_handling

   Illuminate\Database\QueryException

  SQLSTATE[25P02]: In failed sql transaction: 7 current transaction is aborted, commands ignored until end of transaction block (SQL: alter table "nova_menu_menus" drop column "locale")

  at C:\laragon\www\fck\vendor\laravel\framework\src\Illuminate\Database\Connection.php:678
    674รขโ€“โ€ข         // If an exception occurs when attempting to run a query, we'll format the error
    675รขโ€“โ€ข         // message to include the bindings with SQL, which will make this exception a
    676รขโ€“โ€ข         // lot more helpful to the developer instead of just the database's errors.
    677รขโ€“โ€ข         catch (Exception $e) {
  รขลพล“ 678รขโ€“โ€ข             throw new QueryException(
    679รขโ€“โ€ข                 $query, $this->prepareBindings($bindings), $e
    680รขโ€“โ€ข             );
    681รขโ€“โ€ข         }
    682รขโ€“โ€ข

  1   C:\laragon\www\fck\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDO\Exception.php:18
      Doctrine\DBAL\Driver\PDO\Exception::("SQLSTATE[25P02]: In failed sql transaction: 7 current transaction is aborted, commands ignored until end of transaction block")

  2   C:\laragon\www\fck\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOStatement.php:117
      Doctrine\DBAL\Driver\PDO\Exception::new(Object(PDOException))

I've tried the solution #62 (comment). Here are the results:

  • Migrates run successfully
  • I can create menus
  • I can create Items
  • I can't nest items
  • I can't duplicate items (it says menuItem column does not exist in nova_menu_menu_items)

Something is really broken when db is PostgreSQL because everything is Ok on another project with mySQL 5.7

Error run migration on laravel 7.x

Migrating: 2019_11_08_000000_create_menus_table

   ParseError

  syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ',' or ')'

  at D:\sitios\unicesar\vendor\optimistdigital\nova-menu-builder\src\MenuBuilder.php:93
    89|             foreach ($rawFields as $field) {
    90|                 // Handle Panel
    91|                 if ($field instanceof \Laravel\Nova\Panel) {
    92|                     array_map(
  > 93|                         fn ($_field) => ($templateFields[] = $handleField($_field)),
    94|                         $field->data
    95|                     );
    96|                     continue;
    97|                 }

  1   D:\sitios\unicesar\vendor\composer\ClassLoader.php:322
      Composer\Autoload\includeFile("D:\sitios\unicesar\vendor\composer/../optimistdigital/nova-menu-builder/src/MenuBuilder.php")

  2   [internal]:0
      Composer\Autoload\ClassLoader::loadClass("OptimistDigital\MenuBuilder\MenuBuilder")

   Whoops\Exception\ErrorException

Events for hooking

Are there any events that are emitted when menu item is saved? It would be great if there is one as I'm caching the menu like this:

$categoriesMenu = Cache::rememberForever( 'categoriesMenu', function () {
      return nova_get_menu_by_slug( 'categories' );
} );

I would like to clear that cache when the item saved like this:

Cache::forget('categories');

I'm not sure if there are some events and if the standard observers would work.

How to apply policy to this package?

i am trying to hide entire menu on the side bar for users who doesn't has permissions. I created MenuPolicy and when i return false for viewAny on MenuPolicy, it's still shows Menus Link on sidebar. When i click it it's gives me 403 which is right behavior since i returned false in the policy to viewAny. Is there something missing or am i doing it wrong way?

use App\User;
use OptimistDigital\MenuBuilder\Models\Menu;
use Illuminate\Auth\Access\HandlesAuthorization;

class MenuPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view any menus.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function viewAny(User $user)
    {
        return false;
    }
...
namespace App\Providers;

use App\Policies\MenuPolicy;
use App\Policies\RolePolicy;
use App\Policies\PermissionPolicy;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Gate;
use Spatie\Permission\Models\Permission;
use OptimistDigital\MenuBuilder\Models\Menu;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        Role::class => RolePolicy::class,
        Permission::class => PermissionPolicy::class,
        Menu::class => MenuPolicy::class,
    ];
...

some Nova translations are overwriten or broken

Hi, after installation of you package, some of my nova translations are changed, but they are not in your translation file, so there must be a bug..

for example

before: "Kunde erstellen" , after installation "Create Kunde"..

Laravel 7.4
nova 3.12

getOptions sorting

Hi,
I've created custom menu item type. Everything seems to be working as expected expect that getOptions method ignores any type of sorting (e.g. orderBy, sortBy). Records are always sorted by id. Category model doesn't have global sorting defined.

public static function getOptions($locale): array {
    return Category::query()
        ->orderBy('title')
        ->get()
        ->pluck('title', 'id')
        ->toArray();
}

Small css issue

The expand icon is not positioned right:

image

Should be fixed by adding the pt-4 class to the button.

Migrate:refresh fails

Its not possible to rollback/refresh one of the migrations. It should drop the foreign key before removing the index.

This file: 2019_11_08_000001_add_locale_parent_id_to_table.php

$table->dropForeign('menus_locale_parent_id_foreign');
$table->dropUnique('menus_locale_parent_id_locale_unique');
$table->dropColumn('locale_parent_id');

Might also be a good idea to mention how to publish the migrations if people wish to tweak them. They contain alot of logic I dont need :) I dont want a migration to delete anything I havent asked it to :)

$request using private attribute

In the MenuResource::class you are using $request->locale, which is a private attribute

You should change it to this

$request->getLocale();

Turn off nestable

Hello,

thanks for the great package.
Is there a way to turn off the nestable-feature?
I want to prevent submenus!

Thx!

No menu displayed

Hello Optimists

I do not understand the role of "Custom MenuLinkable classes".

Do I have to provide one class per menu choice?

After following your guide, I am able to input menus and choices, make choices hierarchical by dragging them, but the menus on the left side of the Nova dash board is still the sorted list of resources.

Best regards
Bernard
bernard@ballesta;fr

Screen copy:
screenshot-127 0 0 1_8000-2020 06 04-19_59_44

Parameters saving like empty string in DB

Hello!

Sending MenuItem data with empty string ""
image

In my db (MySQL 8.0.14) it saving like empty string too:
image

And after, i have problem with methods getDisplayValue() and getValue() in my custom linkable models

I resolved for my models (remove type for parameter)

public static function getDisplayValue($value = null, $parameters = null)

But i have problem with MenuItemStaticURL becouse $parameters must be array or null

May be default value for parameters in NovaMenu.vue should be null?

Or i have another resolve for this problem?

issue with linkable_models

i have
class PageLinkable extends MenuLinkable
and in the getOptions method i have defined (as suggested in the README)
return Page::all()->pluck('title', 'id');
but it returns a collection not an array. i thought i could simply use the reponse of Model::all here ...

Problem creating my first menu

I have a fresh installation of Laravel 8, Nova, and the nova-menu-builder package and I'm trying to create my first menu.
But when I try to create, it asks me to provide a menu from a dropdown that is empty.

Which menu can I select if this is my first menu?
What am I missing?

The documentation doesn't address this issue, or if it does it's not clear to me.

I posted the same question on StackOverflow, here you can see also a print screen.
https://stackoverflow.com/questions/64160041/how-to-create-my-first-menu-in-laravel-nova-using-nova-menu-builder

Feature Request: add method to exclude menu item from list

Iโ€™m using a custom MenuItemType, where Iโ€™m connecting pages from a Page model to the menu items.
When Iโ€™m deleting the related page and the "relation" breaks, the menu item is still displaying in Nova as well as in front-end via nova_get_menu_by_slug('my-menu').

Maybe to achieve this by writing return false (or something similiar):

public static function getValue($value = null, array $data = null, $locale)
{
	$page = \App\Page::find($value);

	if (!empty($page))
    	return $page->slug; // success: include

    return false; // error: exclude from list
}

inside getDisplayValue it could be disabled in the list-view.

How to prevent auto migration?

The automigration feature is nice to have for a single tenant websites but for multi tenancy,sometimes we dont want a menu installed at the system site.

Right now I have to create a migration file with empty up() and down() to stop the package from auto creating the menu database table. Perhaps it would be cleaner if the package dont auto install?

Request to load menu items fails with 404 status

Just starting using your great package and I have an issue when editing / viewing a menu. The request supposed to fetch the menu items fails with a NotFoundHttpException :

Screen Shot 2021-03-02 at 15 49 43

The request endpoint is /nova-vendor/nova-menu/menu/5?locale=fr

Here is my config file:

<?php

return [
    /*
    |------------------|
    | Required options |
    |------------------|
    */


    /*
    |--------------------------------------------------------------------------
    | Table names
    |--------------------------------------------------------------------------
    */

    'menus_table_name' => 'nova_menu_menus',
    'menu_items_table_name' => 'nova_menu_menu_items',


    /*
    |--------------------------------------------------------------------------
    | Locales
    |--------------------------------------------------------------------------
    |
    | Set all the available locales as either [key => name] pairs, a closure
    | or a callable (ie 'locales' => 'nova_get_locales').
    |
    */

    'locales' => ['fr' => 'French'],


    /*
    |--------------------------------------------------------------------------
    | Menus
    |--------------------------------------------------------------------------
    |
    | Set all the possible menus in a keyed array of arrays with the options
    | 'name' and optionally 'menu_item_types' and unique.
    /  Unique is true by default
    |
    | For example: ['header' => ['name' => 'Header', 'unique' => true, 'menu_item_types' => []]]
    |
    */

    'menus' => [
        'main' => [
            'name' => 'Menu principal',
            'unique' => true,
            'menu_item_types' => []
        ]
    ],


    /*
    |--------------------------------------------------------------------------
    | Menu item types
    |--------------------------------------------------------------------------
    |
    | Set all the custom menu item types in an array.
    |
    */

    'menu_item_types' => [],


    /*
    |--------------------------------|
    | Optional configuration options |
    |--------------------------------|
    */


    /*
    |--------------------------------------------------------------------------
    | Resource
    |--------------------------------------------------------------------------
    |
    | Optionally override the original Menu resource.
    |
    */

    'resource' => OptimistDigital\MenuBuilder\Nova\Resources\MenuResource::class,


    /*
    |--------------------------------------------------------------------------
    | MenuItem Model
    |--------------------------------------------------------------------------
    |
    | Optionally override the original Menu Item model.
    |
    */

    'menu_item_model' => OptimistDigital\MenuBuilder\Models\MenuItem::class,


    /*
    |--------------------------------------------------------------------------
    | Auto-load migrations
    |--------------------------------------------------------------------------
    |
    | Allow auto-loading of migrations (without the need to publish them)
    |
    */

    'auto_load_migrations' => true,


];

Thanks in advance

Add prefix to migrations table name

https://github.com/optimistdigital/nova-menu-builder/blob/c759cf2b06086039f9e04e4932da3f5c87f4085b/database/migrations/2019_11_08_000000_create_menus_table.php#L23

Add prefix to migrations table name to avoid following error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'myProject.migrations' doesn't exist

For example:

$prefix = config( 'database.connections.' . env("DB_CONNECTION") . '.prefix' );

$existingMigration = DB::select("SELECT migration AS name FROM $prefix migrations WHERE migration LIKE '%create_menus_table'");

Migration failed when using PostgreSQL

When I using PostgreSQL in my app, the following error occurs:

Illuminate\Database\QueryException  : SQLSTATE[42703]: Undefined column: 7 ERROR:  column "%create_menus_table"does not exist.

Creating a MenuPolicy

Hi there,

I am trying to create a menu policy since according to this PR it should be available: #21

I created a MenuPolicy with php artisan make:policy MenuPolicy --model=Menu then changed the actual model to
use OptimistDigital\MenuBuilder\Models\Menu; but it does not seem to have any effect.. Am I missing something obvious here? :D

I would love to PR the actual documentation of this feature in case you could explain to me how it actually works?

Thanks!

Call to undefined method CustomMenuLinkable::getType()

I follow the instruction and end up with this error:
Call to undefined method CustomMenuLinkable::getType().

I tried to implement a getType method, something like that:

public static function getType()
    {
        // Example usecase
        // return 'Page Link';
        return [];
    }

But it didn't show me the value input in the menu item creating form.

How do I get a styled select for my custom menu item type

Hi there, thanks a lot for this nice package!

I only don't know how to make this here become a regular select dropdown:

CleanShot 2020-10-04 at 17 15 09@2x

And I'm not sure what I'm expected to add here (maybe the two things are connected??):

CleanShot 2020-10-04 at 17 16 48@2x

Thanks again! Sebastian

Issues with custom menus

I have custom menu's setup as per the docs. The fields appear in Nova when creating an item, and save in the database in the "data" field as json. The problem I have though is that when editing a menu item, the data is not populated, the fields are blank again. Somehow it's not pulling in the existing data.

Here is the content of my custom menu class:

<?php

namespace App\MenuItemTypes;

use Laravel\Nova\Fields\Trix;
use OptimistDigital\MenuBuilder\MenuItemTypes\MenuItemTextType;

abstract class CustomMenuItemType extends MenuItemTextType
{

	/**
	 * Get the menu link identifier that can be used to tell different custom
	 * links apart (ie 'page' or 'product').
	 *
	 * @return string
	 **/
	public static function getIdentifier(): string {
		// Example usecase
		// return 'page';
		return 'pathway';
	}

	/**
	 * Get menu link name shown in  a dropdown in CMS when selecting link type
	 * ie ('Product Link').
	 *
	 * @return string
	 **/
	public static function getName(): string {
		// Example usecase
		// return 'Page Link';
		return 'Pathway';
	}

	/**
	 * Get list of options shown in a select dropdown.
	 *
	 * Should be a map of [key => value, ...], where key is a unique identifier
	 * and value is the displayed string.
	 *
	 * @return array
	 **/
	public static function getOptions($locale): array {
		// Example usecase
		// return Page::all()->pluck('name', 'id')->toArray();
		return [];
	}

	/**
	 * Get the subtitle value shown in CMS menu items list.
	 *
	 * @param null $value
	 * @param array|null $data The data from item fields.
	 * @param $locale
	 * @return string
	 **/
	public static function getDisplayValue($value = null, array $data = null, $locale) {
		// Example usecase
		// return 'Page: ' . Page::find($value)->name;
		return $value;
	}

	/**
	 * Get the value of the link visible to the front-end.
	 *
	 * Can be anything. It is up to you how you will handle parsing it.
	 *
	 * This will only be called when using the nova_get_menu()
	 * and nova_get_menus() helpers or when you call formatForAPI()
	 * on the Menu model.
	 *
	 * @param null $value The key from options list that was selected.
	 * @param array|null $data The data from item fields.
	 * @param $locale
	 * @return any
	 */
	public static function getValue($value = null, array $data = null, $locale)
	{
		return $value;
	}

	/**
	 * Get the fields displayed by the resource.
	 *
	 * @return array An array of fields.
	 */
	public static function getFields(): array
	{
		return [
			Trix::make('description'),
			Trix::make('importance'),
			Trix::make('meaning'),
		];
	}

	/**
	 * Get the rules for the resource.
	 *
	 * @return array A key-value map of attributes and rules.
	 */
	public static function getRules(): array
	{
		return [];
	}

	/**
	 * Get data of the link visible to the front-end.
	 *
	 * Can be anything. It is up to you how you will handle parsing it.
	 *
	 * This will only be called when using the nova_get_menu()
	 * and nova_get_menus() helpers or when you call formatForAPI()
	 * on the Menu model.
	 *
	 * @param null $data Field values
	 * @return any
	 */
	public static function getData($data = null)
	{
		return $data;
	}
}

Missing bracket in documentation

There is missing a bracket in your documentation of the custom menu class

public static function getValue($value = null, array $parameters = null)
    // Example usecase
    // return Page::find($value);
    return $value;
}

should be

public static function getValue($value = null, array $parameters = null)
{
    // Example usecase
    // return Page::find($value);
    return $value;
}

IDEA: menu builder field

Just a faint idea, but if a menu builder field was added to work along side so you could link menu->model that would be cherry on top ๐Ÿ’ƒ

nova_get_menu

Does this only return JSON?

I thought this would have some logic to output HTML as well?

exception during migration

I was just about to test the package, but it gives me error during migrate. Here's the exception:

Migrating: 2020_09_15_000000_rework_locale_handling

   Illuminate\Database\QueryException 

  SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'locale' doesn't exist in table (SQL: alter table `nova_menu_menus` drop `locale`)

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
    667|         // If an exception occurs when attempting to run a query, we'll format the error
    668|         // message to include the bindings with SQL, which will make this exception a
    669|         // lot more helpful to the developer instead of just the database's errors.
    670|         catch (Exception $e) {
  > 671|             throw new QueryException(
    672|                 $query, $this->prepareBindings($bindings), $e
    673|             );
    674|         }
    675| 

      +11 vendor frames 
  12  database/migrations/2020_09_15_000000_rework_locale_handling.php:83
      Illuminate\Support\Facades\Facade::__callStatic("table")

      +22 vendor frames 
  35  artisan:37
      Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

it fails the last migration "2020_09_15_000000_rework_locale_handling"

Any way I can fix this?

Custom Type do not show in Menu items type

I followed your example, I added an abstract class in \App\MenuItemsType called PageMenuItemsType

namespace OptimistDigital\MenuBuilder\MenuItemTypes;

use App\Models\Page;

abstract class PageMenuItemType extends BaseMenuItemType
{

    public static function getIdentifier(): string { 
        return 'page';
    }

    public static function getName(): string {
        return 'Page Link';
    }

    public static function getOptions($locale): array {
        return Page::all()->pluck('title', 'id')->toArray();
    }

    public static function getDisplayValue($value = null, array $data = null, $locale) {
        return Page::find($value)->title;
    }

    public static function getValue($value = null, array $data = null, $locale)
    {
        return $value;
    }

    public static function getFields(): array
    {
        return [];
    }

    public static function getRules(): array
    {
        return [];
    }


    public static function getData($data = null)
    {
        return $data;
    }
}

Then I edited the published config in nova-menu.php:
(I removed some comments for clarity)

<?php

return [
    /*
    |------------------|
    | Required options |
    |------------------|
    */

    'menus_table_name' => 'nova_menu_menus',
    'menu_items_table_name' => 'nova_menu_menu_items',   

    'locales' => 'nova_get_locales',

    'menus' => [
         'header' => [
             'name' => 'Principal',     
             'menu_item_types' => []
         ],
         'footer' => [
            'name' => 'Pied de page',            
            'menu_item_types' => []
        ]
    ],


    /*
    |--------------------------------------------------------------------------
    | Menu item types
    |--------------------------------------------------------------------------
    |
    | Set all the custom menu item types in an array.
    |
    */

    'menu_item_types' => [
        \App\MenuItemTypes\PageMenuItemType::class,
    ],

    /*
    |--------------------------------|
    | Optional configuration options |
    |--------------------------------|
    */
    'resource' => OptimistDigital\MenuBuilder\Nova\Resources\MenuResource::class,
    'menu_item_model' => OptimistDigital\MenuBuilder\Models\MenuItem::class,
    'auto_load_migrations' => true;
];

I'm missing something?

Fresh installation doesn't work

After fresh installation, getting this error SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'locale' doesn't exist in table (SQL: alter table 'nova_menu_menus' drop 'locale') while running migrations.

Environment:
package: 5.2.5
laravel: 8.26.1
nova: 3.21.0

locale not autoloaded

Hi sorry for an opening issue

I have a question, the menu is auto-translated or the locale field is just for grouping propose.

The question is based on the point that I'm not getting the right locale when I'm using
nova_get_menu("footer_1")
I'm using ro and ru locale
also they are set for laravellocalization.

Locale config option with callable as array syntax

Looking at the newest release 5.3.0.
https://github.com/optimistdigital/nova-menu-builder/blob/master/src/MenuBuilder.php#L42

is_array is checked before is_callable, which was not the case on earlier version as you can see.
So if i have configured my locales as callable in static method notation:
'locales' => [\App\Facades\Locale::class, 'getSupportedLocaleArray'],
this doesnt work anymore and kinda breaks. I have to change it to a method call as string:
'locales' => \App\Facades\Locale::class . '::getSupportedLocaleArray',

Add custom field to menu item

Hi,
I am building a menu for using in a site. I need to add a custom field for the menu item.
I have many use-cases, but the most common one is a template field, which tells the app how to render the page of the link.

I know I can add a field to the menu itself, but this is not enough.
I don't want to let my content editors add to via the json field. it is a pitfally way to add data.

Thanks

Link to nova-page-manager

Howdy.

Wondering if there is a nice way to link up pages created with nova-page-manager.

Can't really see how to add it under linkable_models.

Maybe it's something simple I'm missing?

Error when creating menu

I get this error when creating a menu on a fresh installation of Nova v2.3.0 and nova-menu-builder v1.4.0

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: "{{resourceId}}" (SQL: select count(*) as aggregate from "menus" where "slug" = yooo and "id" <> {{resourceId}} and "locale" = )

I narrowed it down the validation rules in MenuResource.php:

->rules('required', 'max:255', 'unique:menus,slug,{{resourceId}},id,locale,' . $request->locale),

I changed the rules like so:

->rules('required', 'max:255', 'unique:menus,slug')
->updateRules('required', 'max:255', 'unique:menus,slug,{{resourceId}},id,locale,' . $request->locale),

And now it works.

However, it seems weird to methat I had to do that. Is there anything wrong with my setup?

Error on creating menu, old one disapear after update

After the update, my menu lists disappear from the dashboard:
-also, locales defined in config file also are not on creation form.
-create menu throw error

In console apears an error related to LocaleButton:

image
Error that i receive when i try to create a new menu.
image

{message: "The given data was invalid.", errors: {locale: ["validation.in"]}}
errors: {locale: ["validation.in"]}
message: "The given data was invalid."

Can somebody tell me what is wrong

Laravel Nova: 3.0.1
Laravel: 7.1

Regarding replication, we can't tell a lot regarding actions that were before, we work more than one person. hope that I set enough details

Issues installing

I ran
composer require optimistdigital/nova-menu-builder
and got error:

In MenuBuilderServiceProvider.php line 29:

Class 'Laravel\Nova\Nova' not found

MenuLinkable::getValue() doesn't seem to be called

Created and registered custom MenuLinkable classes per readme. Mostly works and allows selections with dropdown box when creating a menu item. However, cannot set a custom value to store in the "value" field of the menu_items table. Based on the docs, my understanding is that the getValue method of the custom MenuLinkable class should set that. However, that method appears to never be called.

getIdentifier, getName, getOptions, getDisplayValue all seem to be called.

getValue does not seem to be called.

Value stored in database is the option key retrieved in getOptions instead of the return value of getValue

Validation error when attempting to create a static url

Hello!
Perhaps this is user error. I have been unable to create static menu items with the plugin for some reason. The behavior after attempting to create it or edit an existing model menu item, is the item does not save with a validation error that "The value field is required". Looking at the post request, I am indeed seeing the value property is empty and is instead sitting in the label property:

Screen Shot 2020-03-05 at 7 06 18 AM

Anything simple I might be missing? I have replicated this on two separate installs of Laravel 7 running Nova 3.01. Creating menu items associated with models is working great. Also able to create text type menu links, but not entirely sure how these would be used.

Thanks for your time and this great package!

Fields for custom menu item do not appear when switching from one type to another

When editing a menu item and changing the type from something like a Static URL to a custom menu item the fields that have been defined in the getFields method don't appear.

Steps to reproduce:

  • Define a custom menu item with custom fields.
  • Go to the menu builder and add a new item with one of the default types (like Text or Static URL)
  • Edit the menu item
  • Change the type to the custom menu item type
  • Notice that the fields for the custom menu item type don't appear
  • Save the item, edit it again and notice that the fields now do appear

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.