【问题标题】:How to have the checkbox checked when editing my database编辑我的数据库时如何选中复选框
【发布时间】:2021-01-22 21:39:34
【问题描述】:

我有一个数据透视表themes_article,当我创建我的article 时,它在数据透视表中运行良好。

我现在要做的是,当我在编辑一篇文章时,我已经选中的复选框需要被选中。

这是我的代码:

@foreach ($themes as $theme)  
  <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="themeCheckbox[{{$theme->theme_id}}]" value="1" {{ $article->themeCheckbox[{{$theme->theme_id}}] || old('themeCheckbox[{{$theme->theme_id}}]', 0) === 1 ? 'checked' }} >
      <label class="form-check-label">{{ $theme->nom_theme }}</label>
  </div>
@endforeach

我正在使用它来将我的数据插入到我的数据透视表中(它运行良好):

  $themes = Theme::whereIn('theme_id', array_keys($data['themeCheckbox']))->get();
  $article->save();
  $article->theme()->attach($themes);

我的函数将更新我的数据:

public function editer_article(Request $request, $idArticle)
{
    $data = $request->validate([ // $data = $this->validate($request
        'titreArticle' => 'bail|required|between:5,40',
        'typeArticle' => 'bail|required',
        'themeCheckbox' => 'required',
        'themeCheckbox.*' => 'required',
        'contenuArticle' => 'bail|required'
        
    ]);
    $type_articles = Type_article::findOrFail($data['typeArticle']);
    $article = Article::where('id_article',$idArticle)->firstOrFail();
    $article->type_article()->associate($type_articles);
    $themes = Theme::whereIn('theme_id', array_keys($data['themeCheckbox']))->get();
    $article->titre = $data['titreArticle'];
    $article->contenu = $data['contenuArticle'];

    $article->save();
    $article->theme()->sync($themes);

    return view('admin/article/admin_validation_edition');
}

我遇到了这个错误:

 syntax error, unexpected '{', expecting ']' (View:

我想我没有很好地使用输入中的条件......

真诚的

【问题讨论】:

  • 它不喜欢嵌套的“{{ }}”大括号。
  • 是的,但我需要放它们,不是吗?
  • 是的,你需要它们,但不是嵌套的。您是否尝试使用来自Stefano 的建议答案?
  • 自 1 周以来我一直在努力让它发挥作用。是的,我做到了,我在{{ $article-&gt;themeCheckbox[$theme-&gt;theme_id] || old('themeCheckbox[$theme-&gt;theme_id]', 0) === 1 ? 'checked' }} &gt; 行遇到了这个错误syntax error, unexpected ')
  • 我按照你的建议删除了其中一个嵌套,现在我有了这个:themeCheckbox[$theme-&gt;theme_id] || old('themeCheckbox[$theme-&gt;theme_id]', 0) === 1 ? 'checked' } &gt; conseil 并且对于我拥有的每个主题

标签: laravel laravel-8


【解决方案1】:

这是一个简化的示例,说明如何实现这一目标。

假设您有 ArticleTheme 对象的模型和表,这两个对象都至少有一个 name 字段。 Laravel 中命名数据透视表的约定是按字母顺序组合单个模型名称。所以为此它将是article_theme。此表至少应包含article_idtheme_id 的字段。

数据库/迁移/create_article_theme_table.php

Schema::create('article_theme', function (Blueprint $table) {
    $table->id();
    $table->foreignId('article_id')->constrained();
    $table->foreignId('theme_id')->constrained();
    $table->timestamps();
});

Article 模型中定义它与Theme 的关系。我还添加了一个方便的方法来检查 Theme 是否与视图中使用的 Article 相关联。

app/Models/Article.php

class Article extends Model
{
    use HasFactory;

    public function themes()
    {
        return $this->belongsToMany(Theme::class);
    }

    /**
     * convenience function for checking if a theme is associated to the article
     */
    public function scopeHasTheme(\Illuminate\Database\Eloquent\Builder $builder, Theme $theme)
    {
        return $this->themes()->where('theme_id', $theme->id)->exists();
    }
}

如果你愿意,你可以为你的 Theme 模型做相反的事情。

app/Models/Theme.php

class Theme extends Model
{
    use HasFactory;

    public function articles()
    {
        return $this->belongsToMany(Article::class);
    }
}

定义一些路由来显示您的Article 表单和另一个处理它。

routes/web.php

// define a route to show the form for editing an existing Article
Route::get('/articles/{article}', [\App\Http\Controllers\ArticleController::class, 'show'])
    ->name('articles.show');

// define a route to process the update Article form submission
Route::put('/articles/{article}', [\App\Http\Controllers\ArticleController::class, 'update'])
    ->name('articles.update');

在您的 ArticleController 上构建函数

app/Http/Controllers/ArticleController.php

class ArticleController extends Controller
{
    // process the form submission
    public function update(Request $request, Article  $article)
    {
        $article->themes()->sync($request->themes);

        return redirect(route('articles.show', $article));
    }

    // display the form passing through the article and all themes
    public function show(Article $article)
    {
        return view('articles.show', [
            'article' => $article,
            'themes' => Theme::all()
        ]);
    }
}

视图是“魔法”发生的地方。我们在Article 模型上使用hasTheme 函数来检查给定的Theme 是否与Article 相关联,如果是,则将checked 属性添加到checkbox

resources/views/articles/show.blade.php

<form action="{{ route('articles.update', $article) }}" method="POST">
    @csrf
    @method("PUT")

    <h4>{{ $article->name }}</h4>

    @foreach ($themes as $theme)
        <div>
            <input type="checkbox" name="themes[]" value="{{ $theme->id }}"  
                 id="theme-{{ $theme->id }}" @if($article->hasTheme($theme)) checked @endif>
            <label for="theme-{{ $theme->id }}">{{ $theme->name }}</label>
        </div>
    @endforeach

    <button type="submit">Save</button>
</form>

<hr>

<!-- Output the name of all themes associated to the article for reference -->
<h4>Attached Themes</h4>
@foreach ($article->themes as $theme)
    <div>
        {{ $theme->name }}
    </div>
@endforeach

假设您的数据库中有一些 articlesthemes,例如,如果您转到 /articles/1,您应该看到您的文章以及数据库中每个 themecheckbox 以及与你的articlechecked

【讨论】:

    【解决方案2】:

    确保你没有错字。导致其难以追踪。我不知道你的控制器在哪里,那是什么类型的?创造或其他东西。您可以分享更多详细信息...

    【讨论】:

    • 我真的很困惑如何做到这一点。我有一个AdminControllerediter_article(我已经用这个函数编辑了我的帖子)。这是一个post,因为它正在将数据更新到数据库中。
    【解决方案3】:

    正如@Unflux 正确概述的那样,以下 sn-p 中的嵌套花括号不是必需的:

    <input
       class="form-check-input"
       type="checkbox"
       name="themeCheckbox[{{$theme->theme_id}}]"
       value="1"
       {{ $article->themeCheckbox[$theme->theme_id] || old('themeCheckbox[$theme->theme_id]', 0) === 1 ? 'checked' }} >
    

    【讨论】:

    • 在我看到的每一个帖子中,他们都把大括号放在$article-&gt;themeCheckbox...之前,没用吗?
    【解决方案4】:
    <label for="gender">Gender: </label>
    <div class="custom-control custom-radio custom-control-inline">
        <input class="custom-control-input" id="male" name="gender"
            type="radio" value="Male"
            {{ $dealer->gender == 'Male' ? 'checked' : '' }} />
        <label class="custom-control-label" for="male">Male</label>
    </div>
    <div class="custom-control custom-radio custom-control-inline">
        <input class="custom-control-input" type="radio" id="female"
            name="gender" value="Female"
            {{ $dealer->gender == 'Female' ? 'checked' : '' }} />
        <label class="custom-control-label" for="female">Female</label>
    </div>
    <div class="custom-control custom-radio custom-control-inline">
        <input class="custom-control-input" type="radio" id="na"
            name="gender" value="NotApplicable"
            {{ $dealer->gender == 'NotApplicable' ? 'checked' : '' }} />
        <label class="custom-control-label" for="na">N/A</label>
    </div>
    
    
    

    【讨论】:

    • 我不明白...我有一个数据透视表themes_articles,我的article 表中没有引用theme。另外,我有一个foreach 循环,它将显示每个复选框。我真的很困惑,真的不了解系统来做这件事......
    • dealer 在你的情况下是什么?数据透视表?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    相关资源
    最近更新 更多