我想在用户输入标题时自动生成 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>
问题是:
当我在
Title of news
中输入文本时,它不会实时更改。因为它不会实时更改,所以它不能正确保存 slug。
例:
当我输入新闻Title
字段时:Apple iPhone 7
->单击按钮保存。这些字段slug
不包含任何值。
接下来,我将新闻Title
更改为Apple have plan release IOS 11
->单击按钮保存。数据库中slug
字段更改为Apple iPhone 7
。
你可以在gif上看到:
http://i.imgur.com/JD0TbG8.gif
您的控制器:
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>
我没有尝试过,但应该可以工作。您可能需要适应您的系统,但想法就在这里。