sleeping-owl / admin

Administrative interface builder for Laravel
http://sleeping-owl.github.io/
MIT License
504 stars 259 forks source link

how to use validation at the formItem::custom() method ? #189

Open danpai88 opened 9 years ago

danpai88 commented 9 years ago

hi as the title, I use the custom form field and i want to bind some "validation" when the form commit ,when i use 'required unique' in the FormItem::custom()->callback() method,i get a error "can not found the method",Someone can tell me how to use the "validation" at the "custom form field", thanks

johnshepherd commented 9 years ago

It doesn't seem to be possible. See #145.

danpai88 commented 9 years ago

@johnshepherd can you show me an example ?? I have trouble this problem a few days, thakns!!

johnshepherd commented 9 years ago

Sure, here's a colour picker that I built. Open app/admin/bootstrap.php and add in your class:

FormItem::register('colorPicker', \MyPackage\FormItems\ColorPicker::class);

Create the file itself (I based this on the existing class for the 'text' form item type):

<?php namespace MyPackage\FormItems;

use SleepingOwl\Admin\FormItems\NamedFormItem;
use SleepingOwl\Admin\AssetManager\AssetManager;

class ColorPicker extends NamedFormItem
{
    use Renderable;

    protected $view = 'mypackage::admin.form_items.hex';

    public function initialize()
    {
        parent::initialize();

        AssetManager::addScript(asset('/packages/mypackage/vendor/bootstrap-colorpicker/js/bootstrap-colorpicker.min.js'));
        AssetManager::addStyle(asset('/packages/mypackage/vendor/bootstrap-colorpicker/css/bootstrap-colorpicker.min.css'));
    }
}

Create the view defined in the $view variable above (again this is mostly taken from the built in view for a standard text form item:

<div class="form-group {{  $errors->has($name) ? 'has-error' : '' }}">
    <label for="{{ $name }}">{{ $label }}</label>

    <div class="input-group input-{{ $name }}">
        <input name="{{ $name }}" type="text" id="{{ $name }}" value="{{ $value }}" class="form-control" />
        <span class="input-group-addon"><i></i></span>
    </div>

    @include(AdminTemplate::view('formitem.errors'))
</div>

<script>
    $(function(){
        $('.input-{{ $name }}').colorpicker({
            'format' : 'hex'
        });
    });
</script>

Add it into your $form->items in the same way as you usually do:

FormItem::colorPicker('hex', 'Hexadecimal colour')->required()

And that's about it I think.