0

我想在用户输入标题时自动生成 slug。

<div class="form-group">
    <label for="name">Title of News</label>
    <input type="text" class="form-control" id="name" name="name"
            placeholder="Enter your title of news"
            value="@if(isset($news->name)){{ old('name', $news->name) }}@else{{old('name')}}@endif">
</div>

<div class="form-group">
    <label for="slug">Slug</label>
    <input type="text" class="form-control" id="slug" name="slug"
        placeholder="slug"
        {{!! isFieldSlugAutoGenerator($dataType, $dataTypeContent, "slug") !!}}
        value="@if(isset($news->name)){{ str_slug($news->name, '-') }}@endif">
</div>

<script>
    $('document').ready(function () {

        $('#slug').slugify();
    });
</script>

问题是:

  1. 当我在Title of news.

  2. 因为它不会实时更改,所以它不能正确保存 slug。

例子:

当我输入Title新闻字段时:Apple iPhone 7->单击按钮保存。这些字段slug不包含任何值。

接下来,我将Title新闻更改为Apple have plan release IOS 11-> 单击按钮保存。数据库中的字段slug更改为Apple iPhone 7

你可以在 gif 中看到:

http://i.imgur.com/JD0TbG8.gif

4

1 回答 1

2

你的控制器:

function store(Request $request) {
  $this->validate($request, [
    'title' => 'required'
  ]);

  $news = News::create($request->all());
  $news->slug = str_slug($request->title, '-');
  $news->save();

  return redirect()->back();
}

你的看法:

<div class="form-group">
  <label for="name">Title of News</label>
  <input type="text" class="form-control" id="name" name="name"
  placeholder="Enter your title of news"
  value="@if(isset($news->name)){{ old('name', $news->name) }}@else{{old('name')}}@endif">
</div>
<p>The slug will be <span id="slug"></span></p>

<script>
  $('document').ready(function () {

    $(document).on('change', 'input#name', function() {
      var slug = slugify($(this).val());
      $('span#slug').text(slug);
    });

  });

  function slugify(text)
  {
    return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');            // Trim - from end of text
  }
</script>

我没试过,但应该可以。您可能需要适应您的系统,但想法就在这里。

于 2017-07-22T09:11:37.837 回答