简体   繁体   中英

Get selected value from select_from_array field using laravel 5.2 Backpack

I am using Laravel 5.2 Backpack in my new project where I have a select_from_array field in my form, depending upon the selected value I want data to be displayed in another select_from_array field. Don't know how to do that. Please help me with this. This is my code

Controller.php

public function __construct()
{
    if (Request::segment(3) == 'create') {
        $parentField1 = [
        'name' => 'cat_id',
        'label' => 'Category',
        'type' => 'select_from_array',
        'options' => $this->categories(),
        'allows_null' => false,
        ];
        $parentField = [
            'name' => 'subCat_id',
            'label' => 'SubCategory',
            'type' => 'select_from_array',
            'options' => $this->subcategories(),
            'allows_null' => false,
        ];

        array_unshift($this->crud['fields'], $parentField1,$parentField);

    }

public function categories()
{
    $cat = Request::get('cat_id');

    $currentId = 0;
    if (Request::segment(4) == 'edit' and is_numeric(Request::segment(3))) {
        $currentId = Request::segment(3);
    }

    $entries = Category::where('translation_lang', config('app.locale'))->where('parent_id',0)->orderBy('lft')->get();
    if (is_null($entries)) {
        return [];
    }

    $tab = [];
    $tab[0] = 'Root';
    foreach ($entries as $entry) {
        if ($entry->id != $currentId) {
            $tab[$entry->translation_of] = '- ' . $entry->name;
        }
    }
    return $tab;
}

public function subcategories()
{
    $currentId = 0;

    if (Request::segment(4) == 'edit' and is_numeric(Request::segment(3))) {
        $currentId = Request::segment(3);
    }

    $entries = Category::where('translation_lang', config('app.locale'))->where('parent_id','!=' ,0)->orderBy('lft')->get();

    if (is_null($entries)) {
        return [];
    }

    $tab = [];
    $tab[0] = 'Root';
    foreach ($entries as $entry) {
        if ($entry->id != $currentId) {
            $tab[$entry->translation_of] = '- ' . $entry->name;
        }
    }
    return $tab;
}

I want the id of selected option in the subcategories() where I can use the id to get the data.

I think the best way for you is to create a custom field type for this particular purpose, that includes both selects. Follow this procedure . Start from the select2.blade.php file and add the javascript you need to achieve your goal (on change event on first select2, change the options in the next select2).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM