Как установить флажок и снять оба значения? - PullRequest
0 голосов
/ 05 июня 2018

Я работаю над ACL Laravel.В каждой роли есть группа разрешений.Я представляю все разрешения, используя флажок.Когда я отправляю форму, это только проверенное значение разрешений.но я хочу получить все проверенные и непроверенные значения.enter image description here

Когда я нажимаю кнопку Обновить, отображаются только эти значения

[
    {
        "read": "true",
        "create": "true"
    }
]

Я хочу получить значение, подобное этому.

[
    {
        "read": "true",
        "create": "true",
        "delete": "false",
        "update": "false"
    }
]

Я пытаюсь использовать JQuery, но не получил ожидаемого результата.если есть какой-либо другой способ, пожалуйста, предложите.

Моя часть просмотра.

@foreach($role->permissions as $key=>$value)
    <td><input type="checkbox" name="permisssions[{{$key}}]" class="role" value="true"  {{ $value==1 ? 'checked' : '' }}></td>
@endforeach

Моя часть контроллера.

public function role_permissions_update(Request $request, $id)
{
    return array($request->permisssions);

}

Ответы [ 2 ]

0 голосов
/ 06 июня 2018

если единственной проблемой является получение значения для непроверенных флажков, вы можете использовать скрытые входные данные, подобные этому

<input type="hidden" name="permisssions[{{$key}}]" class="role" value="true"  {{ $value==1 ? 'checked' : '' }}>
        <input type="checkbox" name="permisssions[{{$key}}]" class="role" value="true"  {{ $value==1 ? 'checked' : '' }}>

если они установят флажок, вы получите его значение, в противном случае вы получите значениескрытого ввода

0 голосов
/ 06 июня 2018

Вместо того, чтобы выполнять эту работу в пользовательском интерфейсе - вы можете рассмотреть возможность использования в дезинфицирующем устройстве для запросов перед контроллером.Примерно так ...

MyController.php

<?php
namespace App\Http\Controllers;
use App\Http\Requests\MyRequest;

class MyController{
    public function myMethod(MyRequest $request){
        //write code only for valid, sanitized requests.
    }
}

MyRequest.php

namespace App\Http\Requests;

class MyRequest extends SanitizedRequest{

protected static $bools = ['check_box_a','check_box_b'];

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules(){
    return [
        //
    ];
   }
}

SanitizedRequest.php (может быть абстрактным, я думаю)

<?php
namespace App\Http\Requests;


use Illuminate\Foundation\Http\FormRequest;

class SanitizedRequest extends FormRequest{

/**
 * @var bool
 */
private $clean = false;

/**
 * @var array
 */
protected static $arrays = [];

/**
 * @var array
 */
protected static $bools = [];

/**
 * @var array
 */
protected static $nullables = [];

/**
 * @var array
 */
protected static $removeables = [];



/**
 * We will do ALL of our security from middleware.
 *
 * @return bool
 */
public function authorize(){
    return true;
}

/**
 * @return array
 */
public function all($keys = null){
    return $this->sanitize(parent::all($keys));
}

/**
 * @param array $inputs
 *
 * @return array
 */
protected function sanitize(Array $inputs){

    if($this->clean){
        return $inputs;
    }

    // Get the request after middlewares (ie: the way it should be).

    $inputs = $this->request->all();

    $inputs = self::fillStaticDefaults($inputs);
    $inputs = self::numbers($inputs);
    $inputs = self::arrays($inputs);
    $inputs = self::bools($inputs);
    $inputs = self::removeables($inputs);

    if(method_exists($this, 'dynamicDefaults')){
        $inputs = $this->dynamicDefaults($inputs);
    }

    if(method_exists($this, 'preProcessInputs')){
        $inputs = $this->preProcessInputs($inputs);
    }

    $inputs = self::nullables($inputs);

    $this->replace($inputs);
    $this->clean = true;

    return $inputs;

}

/**
 * @param $inputs
 *
 * @return mixed
 */
private static function fillStaticDefaults($inputs){
    if(empty(static::$defaults)){
        return $inputs;
    }

    foreach(static::$defaults as $key => $val){
        if(empty($inputs[$key])){
            $inputs[$key] = $val;
        }
    }

    return $inputs;
}


private static function numbers($inputs){
    foreach($inputs as $k => $input){
        if(is_numeric($input) and !is_infinite($inputs[$k]*1)){
            $inputs[$k] *=1;
        }
    }

    return $inputs;
}

/**
 * @param array $inputs
 *
 * @return array
 */
private static function arrays(Array $inputs){
    foreach(static::$arrays as $array){
        if(empty($inputs[$array])
           or !is_array($inputs[$array])
        ){
            $inputs[$array] = [];
        }
    }

    return $inputs;
}

/**
 * @param array $inputs
 *
 * @return array
 */
private static function bools(Array $inputs){
    foreach(static::$bools as $bool){
        $inputs[$bool] = (!empty($inputs[$bool]) and $inputs[$bool] != '0' and strtolower($inputs[$bool]) != 'false' and $inputs[$bool] != 0) ? 1:0;
    }

    return $inputs;
}

/**
 * @param array $inputs
 *
 * @return array
 */
private static function nullables(Array $inputs){

    foreach($inputs as $k => $input){
        if(is_array($input)){
            $input = self::nullables($input);
            $inputs[$k] = $input;
        }
        if(empty($input) and $input !== 0 and !(in_array($k, static::$bools) or in_array($k, static::$nullables))){
            unset($inputs[$k]);
        }
    }

    foreach(static::$nullables as $null){
        $inputs[$null] = (!empty($inputs[$null])) ? $inputs[$null]:null;
    }

    return $inputs;
}

/**
 * @param array $inputs
 *
 * @return array
 */
private function removeables(Array $inputs){
    if(pos(static::$removeables) == '*'){
        foreach($inputs as $k => $v){
            if(!is_array($v)){
                if(empty($v)){
                    unset($inputs[$k]);
                }
            }else{
                $inputs[$k] = self::removeables($v);
            }
        }

        return $inputs;
    }

    foreach(static::$removeables as $removeable){
        if(empty($inputs[$removeable])){
            unset($inputs[$removeable]);
        }
    }

    return $inputs;
}

}
...