与数据库的laravel下拉列表

i'm a newbie to laravel framework and i just find it's so hard to understanding laravel form usability.... so here is some issue that i face into

First my dropdown should be having my categories name and at the very end of dropdown it will be my specific dropdown add new categories that when i selected will trigger my javascript... and im here is my form code

{{ Form::select('kategori',KategoriArtikel::lists('name','id'),Input::old('kategori'),array('class' => 'form-control', 'onChange' => 'changeFunc(value)')) }}

that will show right value from my database also with right selected value but it's missing my specific dropdown, so i tried to add like this

 <?php 
     $tambah = array('tambah' => 'Tambah Kategori Baru');
     $list = array_merge(KategoriArtikel::lists('name','id'),$tambah); 
 ?>
{{ Form::select('kategori',array(KategoriArtikel::lists('name','id'),$tambah),Input::old('kategori'),array('class' => 'form-control', 'onChange' => 'changeFunc(value)')) }}

but it will generate 2 with different layout (which ugly) and not showing right selected value, so i tried other way

 <?php 
     $tambah = array('tambah' => 'Tambah Kategori Baru');
     $list = array_merge(KategoriArtikel::lists('name','id'),$tambah); 
?>
{{ Form::select('kategori',$list,Input::old('kategori'),array('class' => 'form-control', 'onChange' => 'changeFunc(value)')) }}

and it not generate and my dropdown layout is what it supposed to be but now the is not from my table id anymore but just sequential number 0,1,2,3,etc any solution to that?

Second problem is when i submit my form, it's not working, my field in table is int and when i submit it just not saving/updating so i tried to dd(Input::all()) and my dropdown is returning string of selected option value and it's not saved into my table... so why is that? it also not working for my boolean field that contain tinyint(1)... so basicly all value returning string.

its returning this

array(8) { ["_method"]=> string(3) "PUT" ["_token"]=> string(40) "IspUKdCETMe4Nn3pDI43GI7aJKQfXpupJvQAy1k6" ["simpan"]=> string(6) "simpan" ["judul"]=> string(18) "test "kegiatan" 21" ["kategori"]=> string(1) "9" ["kategori_baru"]=> string(0) "" ["status"]=> string(1) "0" ["content"]=> string(1012) "
I used--and I don't put my arm round your waist,' the Duchess said to herself. 'Of the mushroom,' said the Dormouse, and repeated her question. 'Why did they live at the sides of it, and then turned to the tarts on the twelfth?' Alice went on, 'that they'd let Dinah stop in the shade: however, the moment he was obliged to have wondered at this, but at the Caterpillar's making such a capital one for catching mice--oh, I beg your pardon!' cried Alice hastily, afraid that she had read about them in books, and she at once without waiting for turns, quarrelling all the children she knew, who might do something better with the time,' she said to herself; 'I should like to drop the jar for fear of killing somebody, so managed to swallow a morsel of the house, quite forgetting her promise. 'Treacle,' said the Gryphon: and it sat for a few minutes to see if she had grown up,' she said this, she looked down at her as she wandered about for it, you know--' (pointing with his head!' she said,.

" }

and as you can see ['kategori'] is supposed to be making my field kategori in my table to be 9 but it's not changing anything in my database

well i laravel simplicity but it's very confusing when working with database (can't find any documentation example related to databas retrieving data and so on)

edit:

this is my controller

public function update($id)
{
    $artikel = Artikel::findOrFail($id);

    if(Input::get('simpan')){
        //dd(Input::all());

        $validator = Validator::make($data = Input::all(), Artikel::$rules);

        if ($validator->fails())
        {
            return Redirect::back()->withErrors($validator)->withInput();
        }

        $judul = Input::get('judul');
        $artikel->update($data);

        return Redirect::route('admin.artikels.index')->with('message', 'Artikel ' .$judul. ' Telah berhasil di ubah.');
    }elseif(Input::get('batal')){
        return $this->index();
    }
}

and here is my view

@extends('admin._layouts.admin')

@section('content')
{{ Form::model($artikel, array('route' => array('admin.artikels.update',$artikel->id), 'method' => 'put')) }}
    <div class="panel panel-default">
        <!--button-->
        <div class="panel-heading tooltip-demo">
            {{ Form::submit('Simpan',array('class' => 'btn btn-primary', 'data-toggle' => 'tooltip', 
               'data-placement' => 'top','title' => 'Menyimpan artikel' )) }}
            {{ Form::submit('Batal',array('class' => 'btn btn-default', 'data-toggle' => 'tooltip', 
               'data-placement' => 'top','title' => 'Batal menambah artikel dan kembali ke halaman kelola artikel' )) }}
        </div>
        <!--/button-->
        <div class="panel-body">
            <!--judul-->
            <div class="col-lg-10">
            <div class="form-group">
                {{ Form::label('Judul Artikel') }}
                {{ Form::text('judul',null,array('class' => 'form-control', 'placeholder' => 'Silahkan masukkan judul artikel'))}}
                {{ $errors->first('judul', '<p class="error">:message</p>') }}
            </div>
            </div>
            <!--/judul-->
            <!--kategori-->
            <div class="col-lg-4">
            <div class="form-group">
                {{ Form::label('Kategori') }}
                <?php 
                    $tambah = array('tambah' => 'Tambah Kategori Baru');
                    $list = array_merge(KategoriArtikel::lists('name','id'),$tambah); 
                ?>
                {{ Form::select('kategori',$list,'Pilih Kategori Artikel',array('class' => 'form-control', 'onChange' => 'changeFunc(value)')) }}
            </div>
            </div>
            <!--/kategori-->
            <!--kategori baru-->
            <div class="col-lg-4"  id="pilihan" style="display:none;">
            <div class="form-group">
                {{ Form::label('Kategori Baru') }}
                {{ Form::text('kategori_baru',null,array('class' => 'form-control', 'placeholder' => 'Silahkan masukkan kategori baru', 
                   'maxlength' => '30'))}} 
            </div>
            </div>
            <!--/kategori baru-->
            <!--status-->
            <div class="col-lg-4">
            <div class="form-group">
                {{ Form::label('Status') }}
                {{ Form::select('status',array('0' => 'Tidak diterbikan', '1' => 'Terbitkan'),null, array('class' => 'form-control')) }}
            </div>
            </div>
            <!--/status-->
            <!--artikel pilihan-->
            <div class="col-lg-5">
            <div class="form-group">
                {{ Form::label('Artikel Pilihan') }}
                <div class="input-group">
                <span class="input-group-addon">
                {{ Form::checkbox('pilihan','1',true,array('id' => 'artikelpilihan')) }}
                </span>
                {{ Form::text('null','Tidak',array('class' => 'form-control', 'id' => 'artikeltext' ,'disabled' => 'true'))}}
                </div>
            </div>
            </div>
            <!--/artikel pilihan-->
            <!--content-->
            <div class="col-lg-12">
                {{ Form::label('Isi Artikel') }}
                {{ Form::textarea('content',null,array('style' => 'height:300px')) }}
                {{ $errors->first('content', '<p class="error">:message</p>') }}
            </div>
            <!--/content-->
        </div>
     </div>
{{ Form::close() }}
{{ HTML::script('js/tinymce/tinymce.min.js') }}
<script type="text/javascript">
    tinymce.init({
        selector: "textarea",
        theme: "modern",
        skin: 'light',
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor colorpicker textpattern"
        ],
        toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
        toolbar2: "print preview media | forecolor backcolor emoticons | fontselect fontsizeselect",
        image_advtab: true,
        templates: [
            {title: 'Test template 1', content: 'Test 1'},
            {title: 'Test template 2', content: 'Test 2'}
        ],
        file_browser_callback: RoxyFileBrowser
    });


    function RoxyFileBrowser(field_name, url, type, win) {
      var roxyFileman = '../../../../public/js/tinymce/plugins/fileman/index.html?integration=tinymce4';
      if (roxyFileman.indexOf("?") < 0) {     
        roxyFileman += "?type=" + type;   
      }
      else {
        roxyFileman += "&type=" + type;
      }
      roxyFileman += '&input=' + field_name + '&value=' + document.getElementById(field_name).value;
      tinyMCE.activeEditor.windowManager.open({
         file: roxyFileman,
         title: 'File Manager',
         width: 800, 
         height: 480,
         resizable: "yes",
         plugins: "media",
         inline: "yes",
         close_previous: "no"  
      }, {     window: win,     input: field_name    });
      return false; 
    }
</script>
@stop
dto5637
dto5637 是的,那是我的取消/蝙蝠按钮,所以它与保存在Input::get('simpan')中捕获的数据无关,它将更新我的其他输入,除了下拉,所以像judul和内容将是更新但下拉像kategori,pilihan,状态,很快就不会更新....
大约 6 年之前 回复
douqiandai4327
douqiandai4327 返回$this->index();在您的控制器中带您到您发布代码的视图文件?
大约 6 年之前 回复
doubi3996
doubi3996 你真的不应该在你的视图文件中使用KategoriArtikel::lists('name','id')。它应该在你的控制器中。你能告诉我们你的控制器和视图
大约 6 年之前 回复

2个回答

If I have understood your problem correctly, you want to populate a dropdown based on values from database and also want to display "Select A Category" in the category dropdown. And currently your dropdown values are not being saved.

To populate the dropdown put the following code your controller's method through which you are loading the view file.

$data['kategori'] = KategoriArtikel::lists('name','id');
$data['kategori'][''] = 'Select a kategori';        
return View::make('YOUR_VIEW_FILE', $data); 

In your view file, simple use the following, (same rules apply for other select dropdowns):

{{ Form::select('kategori', $kategori , Input::old('kategori'), array('id' => 'category', 'class' => 'form-control',  )) }} 

The above code basically generates something like this:

<select id="category" class="form-control">
  <option value="">Select a Kategori</option>
  <option value="1">First Kategori</option>
  <option value="2">Second Kategori</option>
</select>

The third parameter in Form::select() expects a default option value, if you provide a value it will compare with option values and display the matched one as selected.

And Your form's method shouldn't be 'method' => 'POST' not 'method' => 'put'

I am using the following code in cases such this you described. In my controller i have

public function create()
    {
        $category1= Category1::lists('category1','id');
        $category2= Category2::lists('category2','id');
       //you can have many select lists in an form
        return      
     View::make('someobject.create',compact('category1','category2'));
    }

and in my someobject.create view

{{Form::open(array('route'=>'someobject.store'))}}
   <div>
    {{Form::label('category1', 'category1')}}  
    {{Form::select('category1',array('' => 'Please select') + $category1) }}
    <span class="errors">{{$errors->first('category1')}}</span>
    {{Form::label('category2', 'category2')}}  
    {{Form::select('category2',array('' => 'Please select') + $category2) }}
    <span class="errors">{{$errors->first('category2')}}</span>
   </div>
   <div>
   {{Form::submit('Save',array('class' => 'btn'))}}
   </div>
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐