Giter Club home page Giter Club logo

html's Introduction

StydeNet Html package

Build Status Downloads Version License

This package contains a collection of Laravel PHP classes designed to generate common HTML components, such as:

  • Menus
  • Alert messages
  • Form fields
  • Collection of radios and checkboxes

This is an extension of the Laravel Collective HTML package and will be very useful if you are working on a custom CMS, an admin panel or basically any project that needs to generate HTML dynamically.

How to install

  1. The preferred way to install this package is through Composer:

Laravel 6.0 users / Laravel 7.0 users:

Install by running composer require "styde/html=~1.8" or adding "styde/html": "~1.8" to your composer.json file and then running composer update.

Laravel 5.8 users:

Install by running composer require "styde/html=~1.7" or adding "styde/html": "~1.7" to your composer.json file and then running composer update.

Laravel 5.7 users:

Install by running composer require "styde/html=~1.6" or adding "styde/html": "~1.6" to your composer.json file and then running composer update.

Laravel 5.6 users:

Install by running composer require "styde/html=~1.5" or adding "styde/html": "~1.5" to your composer.json file and then running composer update.

Laravel 5.5 users:

Install by running composer require "styde/html=~1.4" or adding "styde/html": "~1.4" to your composer.json file and then running composer update.

  1. Next, add the new provider to the providers array in config/app.php (this step is not necessary if you are using Laravel 5.5 with package auto-discovery)
'providers' => [
    // ...
    Styde\Html\HtmlServiceProvider::class,
    // ...
],
  1. Also, you need to register in the app/Http/Kernel.php file the \Styde\Html\Alert\Middleware::class middleware BEFORE the EncryptCookies middleware, for Laravel 5.8 and later the middleware needs to be registered AFTER the StartSession middleware. For Laravel 5.4 and later, it's in the $middlewareGroups array and for previous versions (Laravel 5.3, 5.2, 5.1) it's in the $middleware array:
// For Laravel 5.4 and later
protected $middlewareGroups = [
    // For Laravel 5.8 and later this needs to be after the StartSession middleware
    \Styde\Html\Alert\Middleware::class,
    //...
];

// For Laravel 5.3, 5.2, 5.1
protected $middleware = [
    //...
    \Styde\Html\Alert\Middleware::class,
    //...
];

This middleware is needed to make the alert messages persistent between sessions, after each request is completed.

Please notice that the following global aliases will be automatically available (you don't need to add them):

Alert => Styde\Html\Facades\Alert
Field => Styde\Html\Facades\Field
Menu  => Styde\Html\Facades\Menu
Form  => Collective\Html\FormFacade
Html  => Collective\Html\HtmlFacade

If you plan to use the Access Handler as a standalone class, you will need to add the following alias:

'aliases' => [
    // ...
    'Access' => Styde\Html\Facades\Access::class,
    // ...
],

Optionally, you may also run php artisan vendor:publish --provider='Styde\Html\HtmlServiceProvider' to publish the configuration file in config/html.php and review its options and values.

Usage

Since this package is largely using LaravelCollective/Html, its documentation for forms and fields is applicable to this package.

Sandbox

Build Status

This package aims to stay well documented and unit tested; however, there is another repository that includes integration tests and several routes, so you can clone it to watch the components of this package in action in your browser or run the included integration tests.

Check out the sandbox repository

You can review those examples and tests as another way to learn more about what you can do with this component, besides reading the documentation.

Configuration

This package was created with configuration in mind, if you haven't used this component before, you can simply run:

php artisan vendor:publish --provider='Styde\Html\HtmlServiceProvider'

this will publish all the configuration options to: config/html.php file, where you can explore and read the comments to learn more about the configuration options and their values.

Note: Since the default configuration will be merged with the custom configuration, you don't need to publish the entire configuration in every project; instead, just set the values you need to override.

Read this documentation to learn more about the different configuration options this package provides.

Form Field builder

The Field Builder will allow you to render the full dynamic markup you need for each form field with only one line of code.

If you have used the Laravel Collective HTML component before, you already know the basics, simply replace the alias “Form” with “Field”, for example, replace:

{!! Form::text('name', 'value', $attributes) !!}

With this:

{!! Field::text('name', 'value', $attributes) !!}

Learn more about the field builder

Forms

This package adds the following functionality to the Laravel Collective's Form Builder:

novalidate

Deactivate the HTML5 validation, ideal for local or development environments

//config/html.php
return [
    'novalidate' => true
];

radios

Generate a collection of radios: i.e.:

{!! Form::radios('status', ['a' => 'Active', 'i' => 'Inactive']) !!}

checkboxes

Generate a collection of checkboxes

$options = [
    'php' => 'PHP',
    'js' => 'JS'
];
$checked = ['php'];
{!! Form::checkboxes('tags', $options, $checked) !!}

Learn more about the form builder

Alert messages

This component will allow you to generate complex alert messages.

Alert::info('Your account is about to expire')
    ->details('Renew now to learn about:')
    ->items(['Laravel', 'PHP', 'And more!'])
    ->button('Renew now!', url('renew'), 'primary');
{!! Alert::render() !!}

Learn more about the alert component

Menu generator

Menus are not static elements, sometimes you need to mark the current section, translate items, generate dynamic URLs or show/hide options for certain users.

So instead of adding a lot of HTML and Blade boilerplate code, you can use this component to generate dynamic menus styled for your preferred CSS framework.

To generate a menu simply add the following code in your layout’s template:

{!! Menu::make('items.here') !!}

Learn more about the menu generator

HTML builder

This package extends the functionality of the Laravel Collective’s HTML Builder.

There’s only one extra method for now, but it’s very useful!

Generate CSS classes:

{!! Html::classes(['home' => true, 'main', 'dont-use-this' => false]) !!}

Returns: class="home main"

Learn more about the HTML builder

Helpers

In addition of using the facade methods Alert::message and Menu::make, you can use:

alert('this is the message', 'type-of-message')
menu($items, $classes)

Access handler

Sometimes you want to show or hide certain menu items, form fields, etc. for certain users, with this component you can do it without the need of conditionals or too much extra boilerplate code, just pass one of the following options as a field attribute or menu item value.

  1. callback: a function that should return true if access is granted, false otherwise.
  2. logged: true: requires authenticated user, false: requires guest user.
  3. roles: true if the user belongs to any of the required roles.

i.e.:

{!! Field::select('user_id', null, ['roles' => 'admin']) !!}

Learn more about the access handler

Themes

There are a lot of CSS frameworks out there, this package was created with that in mind, and even though Bootstrap (version 3 and 4) and Bulma are included out of the box, we plan to add more packages in the future (we also invite you to collaborate).

But you can also create your own themes with ease, or modify the existing one:

To change and / or customize the theme, simply run:

php artisan vendor:publish

Then go to config/html.php and change the theme value:

//config/html.php
return [
    'theme' => 'your-theme-here'
];

You can edit and/or create new templates in resources/views/themes/

Learn more about the themes

Internationalization

This package was also created with internationalization in mind.

If you don’t plan to use this feature, you can deactivate translations in the configuration

//config/html.php
return [
    //…
    'translate_texts' => false
    //…
];

But if your project needs to implement more than one language or you want to organize all the texts in resources/lang/ instead of hard coding them in the controllers, views, etc. set 'translate_texts' to true.

Learn more about the internationalization

More documentation

You can find a lot of comments if you dig into the source code, as well as unit tests in the spec/ directory, you can also clone the integration tests repository.

If you have additional questions, feel free to contact me on Twitter (@Sileence) or send me an email to [email protected].

License

The Styde\Html package is open-sourced software licensed under the MIT license.

html's People

Contributors

andrestntx avatar clemir avatar dannyfeliz avatar dimitriacosta avatar helmerdavila avatar israelortuno avatar jlopezcrd avatar joker9050 avatar lsfiege avatar manelgavalda avatar nerones avatar phroggyy avatar ramono avatar satoblacksato avatar sileence avatar socieboy avatar uziel-bueno 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

html's Issues

Problem Translation

Bueno pues nada tengo el siguiente problema:

<div class="form-group">
    <label  class="col-lg-2 col-sm-2 control-label">{{ trans('auth::ui.role.description') }}</label>
    <div class="col-lg-8">

        {!! Form::text('description', null, ['class' => 'form-control']) !!}

    </div>
</div>

Ahora como ves uso las traducciones para los label, y esto me genera un problema al trabajar con tu paquete, porque si coloco una traduccion esta no va a coincidir con el nombre del campo esperado

Checkboxes with only one item bug

Get an wrong name when $options array is only one item.

Code:
{!! Form::checkboxes('remember', ['remember' => 'Recordar'], ['remember']) !!}

Result an input name 'remember[]' :

<div class="checkbox">
    <label>
        <input id="remember_remember" checked="checked" name="remember[]" type="checkbox" value="remember">
        Recordar
    </label>
</div>

Bug in Field::select for multiple select

Use Form::select its different from Field::select for multiple select.

Form::select('fruits[]', ['1' => 'Apple', '2' => 'Banana', '3' => 'Watermelon'], ['1', '3'], ['multiple'])

generate

<select multiple="multiple" name="fruits[]">
      <option value="1" selected="selected">Apple</option>
      <option value="2">Banana</option>
      <option value="3" selected="selected">Watermelon</option>
</select>

and

Field::select('fruits[]', ['1' => 'Apple', '2' => 'Banana', '3' => 'Watermelon'], ['1', '3'], ['multiple', 'empty' => false])

generates

<div id="field_fruits[]" class="form-group"> 
      <label for="fruits[]" class="control-label"> Fruits[] </label> 
      <div class="controls"> 
          <select 1="1" 3="3" class="form-control" id="fruits[]" name="fruits[]">
                <option value="1">Apple</option>
                 <option value="2">Banana</option>
                <option value="3">Watermelon</option>
           </select> 
        </div>
 </div>

Check the select 1="1" ,3="3" and selected attr in options dont work ,ignore the empty => 'false'

Clase "active" Submenu dentro de un submenu

Al hacer un submenu dentro de otro, es decir:
'menu' => [ 'submenu_1' => [ 'submenu_1_1' => [ ] ] ]

y al entrar al submenu_1_1 no genera la clase "active" para menu, únicamente para "submenu_1" y "submenu_1_1" por favor su ayuda, ¿cómo resuelvo esto?

Form::radios not put checked for default.

I am using the "styde / html" version: "~ 1.2".
When using {!! Form::radios('visible', [1 => 'Yes', 0 => 'No'], 1) !!}

I did not get the default selection working, when reviewing the class class Styde \ Html \ FormBuilder, when printing the input of the render I can observe that the condition for the "selected" is fulfilled.

array:2 [▼
  0 => array:5 [▼
    "name" => "visible"
    "value" => 1
    "label" => "Si"
    "selected" => true
    "id" => "visible_1"
  ]
  1 => array:5 [▼
    "name" => "visible"
    "value" => 0
    "label" => "No"
    "selected" => false
    "id" => "visible_0"
  ]
]

However the render output does not set the checked = ""

<div class="radio"> <label> <input id="visible_1" name="visible" type="radio" value="1"> Si </label> </div> <div class="radio"> <label> <input id="visible_0" name="visible" type="radio" value="0"> No </label> </div>

FieldBuilder in Laravel 5.5

verification on attribute required

Al usar el facades Field :: text en la documentación, indica que el atributo requerido puede ser opcional si se coloca 'required' => false, en la versión 5.5 tengo que hacer la siguiente modificación para el atributo pueda trabajar basado en el valor booleano

protected function getRequired($attributes)
{
    if (!array_key_exists('required', $attributes)) {
        return true;
    }
    if (isset($attributes['required'])) {
        return $attributes['required'];
    }
    return false;
}



protected function getHtmlAttributes($type, $attributes, $errors, $htmlId, $required)
{
    $attributes['class'] = $this->getClasses($type, $attributes, $errors);
    $attributes['id'] = $htmlId;
    if ($required && !array_key_exists('required', $attributes)) {
        $attributes[] = 'required';
    }
    unset($attributes['template'], $attributes['label']);
    return $attributes;
}

Undefined index: theme

Instalé Styde/Html en mi laravel 6 y obtengo el siguiente error

Undefined index: theme

me marca la siguiente linea

$this->theme = new Theme($this->app['view'], $this->options['theme'], $this->options['custom']);

vendor\styde\html\src\HtmlServiceProvider.php:110

Field Help

A functionality could be added for all the fields that allows passing an attribute 'help' with its respective value. i.e:

{!! Field::textarea('presentation', ['label' => 'Presentation website (*)', 'rows' => 4, 'help'=> 'Write your two names']) !!}

Result:

<small id="presentation-help" class="form-text text-muted">Write your two names</small>

Support for Laravel 9 and future versions

Good morning and greetings to the developers, I love this package, I use it almost daily, so please don't forget it, I still don't have the level to maintain such a package. I hope they continue to maintain and update it for the current version of Laravel and future versions, or in any case open it up to the community that can maintain it.

Error in persistence of alert messages in session for Laravel 5.8

Alerts are being lost among the requests.

Using middleware \ Styde \ Html \ Alert \ Middleware :: class it is not working.

I'm using alert ('Hello') and then redirect () -> route ('index')

Where in the view of the route index I have the {!! Alert :: render () !!}

It seems that someone already raised a pull request correcting this problem: #120

Input icons

Any chanses we would get icons support?

E.g. for Bulma add icon-left and icon-right to options list. Not sure about boostrap, but i believe they have some icon support too.

<div class="field">
  <p class="control has-icons-left has-icons-right">
    <input class="input" type="email" placeholder="Email">
    <span class="icon is-small is-left"><i class="fas fa-envelope"></i></span>
    <span class="icon is-small is-right"><i class="fas fa-check"></i></span>
  </p>
</div>

La clase active generada en varios items

Al tener urls por ejemplo del tipo

usuarios/roles
usuarios/roles/editar

En el menú se genera la clase "active" para ambas opciones.

¿Cómo se puede solucionar esto?
Gracias

Alert session error

ErrorException in Container.php line 144:
array_merge(): Argument 1 is not an array

cloning html-integration-tests

and going to
html-integration-tests/public/alert/success url

$this->handler->getPreviousMessages() return "null" in Container.php

support for spatie/laravel-html

as laravelcollective/html was abandoned now composer recommends using spatie/laravel-html it would be great if this package has the option to make compatible.

compact(): Undefined variable: 'classes' in PHP 7.3

src/FormBuilder.php is throwing an error using PHP 7.3 on line 144.

The problem appears when using Field::radios with php 7.3 because the way compact works in this php version:
Undefined variables passed to compact will be reported with a notice, they were previously ignored.

Menú activa dos links al mismo tiempo debido al nombre

Buenos días. Estoy agregando links al menú por ejemplo. News y newsletter. Cuando selecciono news queda activo también newsletter debido a que la función hace una búsqueda parcial para agregar la clase active. Cual seria una solución apropiada. Por ahora modifique igualando en la función pero lo hago en el vendor. Pero es algo q no debería hacerse. Quizás creando una funcion. O también podría estar utilizando mal el componente. Gracias por su apoyo.

LICENCE

Hi, I do not see a license choice for this repository.
I note that https://github.com/LaravelCollective/html/blob/5.3/LICENSE.txt is the MIT License.

While your repository is have much contribution that is a good choice for some projects for other people to know about working on a custom CMS, generating HTML dynamicall from you. That you may add a Licence for your repository

Empty option in select

When i tried to generate a select (multiselect), this create a empty option selectable. This happens in common select too.
This is my two suggestions.

  1. No empty field when ['empty' => false]
  2. Disabled option ['empty' => ['Select your option', disabled]].
    Thank you.

add support for laravel 10

Hello @sileence,

I hope this email finds you well. I wanted to express my appreciation for the amazing work you've done with StydeNet/html. This package has been very useful for my project and I am grateful for it.

Since Laravel has recently released version 10, I was wondering if you could consider adding support for this version in your package. I understand it may take time, but I think it would be of great benefit to the user community.

I'm sure many users like me would be grateful for this update. Thanks in advance for your time and effort!

Kind regards,

The template parameter is removed

In FieldBuilder the parameter "template" is removed by getHtmlAttributes (line 696) before $this->getCustomTemplate($attributes) get called (line 701).

Doesn't display errors on "nested" fields

I have problems to display errors on "nested" fields.
For example:
Field::text('address[name]')
Validation returns with errors but the form doesn't display any.

I understand that in this case I can use address_name, but there are more complex escenarios where it's quite a problem.

User multiples Roles

currently only it verifies that the user has role, but if the user has more than one rool?

Carpeta themes personalizable

Image

Estoy realizando un LMS en Laravel el cual trabaja con temas, pero se me esta presentando un conflicto y es que el paquete html de Styde me crea una carpeta llamada themes que exactamente igual a la que yo utilizo para los temas del LMS, e intentado en mover la carpeta de los templates del lms pero igual se ve confuso.

En conclusión, que en el archivo de configuración se pueda definir una nueva ruta para los resources del paquete.

Blade components

Where is this package usually used on Laravel? On Blade files.
So, what about adding blade directives to make it easier for developers?

Custom Components, fails on creation

Custom components can't be defined because, Styde\Html\FormBuider constructor doesn't instantiate internal class attribute view defined on Collective\Html\FormBuilder

url undefined

Estaba probando tu package, detecte que cuando pones logged => true a cada item del menu y cuando vas a generar el menu como no envias la variable url el package no tiene nada para construir el menu.
Solution

ID generation for multiselects

Hi, when generating multiselects with

{!! Field::selectmultiple('categorias[] ......, ['id'=>'categorias] !!}

the id of the generated Field is set to categorias[], causing jquery #('categorias') or #('categorias[]') not finding the select field

In FieldBuilder.php, function doBuild(....)

the code

$id = $this->getHtmlId($name));

can be changed to:

$id = (isset($attributes['id']) ? $attributes['id'] : $this->getHtmlId($name));

to gerate the correct id for this control

Add the reserved word return the input method on FieldBuilder.php

/**
 * Create a form input field.
 *
 * @param string $type
 * @param string $name
 * @param string $value
 * @param array  $attributes
 *
 * @return string
 */
public function input($type, $name, $value = null, $attributes = array())
{
    return $this->build($type, $name, $value, $attributes);
}

Message not display after redirect in version 5.4

Alert message not work for my only a in new installation 5.4 and after redirect

This is the controller:

    public function edit(Consorcio $consorcio)
    {
        return view('consorcio.edit', ['consorcio' => $consorcio]);
    }

    public function update(Request $request, Consorcio $consorcio)
    {
        $consorcio->nombre = $request->get('nombre');

        if( !$consorcio->save() ){
            Alert::danger("Error: No se se guardaron los cambios.");
        } else {
            Alert::success("El consorcio se modificó correctamente.");
        }

        return redirect()->route('consorcio.edit', $consorcio->id);
    }

and in the view (consorcio/edit.blade.php) :

    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div>
                    <p>{!! Alert::render() !!}</p>
                </div>
                ...

The function getDefaultClasses($type) don't work

The classes of html.php file don't work. I tried it part by part and this function has the problem. This function never returns the correct type class and always returns 'form-control' or 'default-class'

Add support for PHP 8

Hello!

I inherited a proejct which uses this great package but we are having issues
installing some dependencies in a PHP 8 environment.

Are there any plans to update it for PHP 8?

Much appreciated.

[develop] Improve syntax of select from

The new select method allows you to chain a call to a new from method to fetch data from the database, the params of this method atm are:

  • table
  • display column
  • value column (default to id)
  • additional query (optional)
        $fields->select('parent_id')
            ->from('menu_items', 'label', 'id', function ($query) {
                $query->whereNull('parent_id')
                    ->orderBy('label', 'ASC');
            })
            ->label('Parent');

I'm looking for ideas to improve this syntax, make it more flexible etc.

Also this needs integration tests.

Alert Middleware

When this line \Styde\Html\Alert\Middleware::class is added to Http\Kernel.php file, the auth views from Laravel 5.2 doesn't work.

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.