Save toggle data into db

Published 5 days ago by esorone

Goodnight,

I'm struggling with saving my toggle data into the database.

I tried numerous options, but no did work

current try. In my view:

                               {{ Form::checkbox('feedbackboolean', 1) }}Ja
                               {{ Form::checkbox('feedbackboolean', 0) }}Nee

Seconds Try: Just a toggle button

<input type="checkbox" name="feedbackboolean" checked data-toggle="toggle" data-on="1" data-off="0">

In my controller:

        $post->feedbackboolean = $request->get('feedbackboolean');

or 

      $post->kennisbankboolean = $request->get('kennisbankboolean', 0);

Or

        $post->feedbackboolean = $request->feedbackboolean;

But unfortunately they did not work. The samples above , are just a sample which I all found online. So somewhere Im misinterpret the solution

The rest of the post form is stored in the database and works as it should be.

What am I missing here.

As always, thanks in advanced.

Best Answer (As Selected By esorone)
Cronix

Yes, it will work it's what I've been saying lol. The problem is your form, or something interfering with it, before it even gets to laravel (or else the checkbox would come through in the $request object when checked).

I'd really urge you to use actual html for your forms, and not to use that form library. Your IDE will alert you if you do things like have 2 open form tags (or any mismatched tags in general), but it won't with that form library.

Cronix
Cronix
5 days ago (727,800 XP)
{{ Form::checkbox('feedbackboolean', 1) }}Ja
// or
<input type="checkbox" name="feedbackboolean">
$post->feedbackboolean = (int) $request->has('feedbackboolean');

The actual value doesn't matter. I just check whether it was present in the request with has() (which returns a boolean) and then cast that to an int. This works very well with 0/1 values.

So if it was checked, it will be in the request, and become a 1. If it wasn't checked, it won't be in the request and will become a 0.

esorone

Hey Cronix,

As always, thanks again. I'm able to store a value, but..

Still one question left. If I check it or don't check it, the value is the same "0" in the database.

Any ideas left?

View:

                    <div class="control-group">
                            <label class="control-label">{{ Form::label('kennisbankboolean', 'Beschikbaar in Kennisbank?') }}</label>
                            <div class="controls">         

                               {{Form::checkbox('kennisbankboolean', 1)}}Ja
                               <hr>
                               <label class="control-label">{{ Form::label('title', 'Wil je feedback geven?') }}</label>
                               {{ Form::checkbox('feedbackboolean',1) }}Ja
                                <hr>
                               <label class="control-label"> {{ Form::label('Feedbacktxt', 'Feedback') }}</label>
                                <div class="controls">
                                {{ Form::textarea('feedbacktxt', null, array('class' => 'span11')) }}
                                <hr>
                            </div>
                        </div>
                    </div>

Controller:

    public function store(Request $request)
    {
        //Validating
       $this->validate($request, [
            'title' => 'required|max:100',
            'channel' => 'required',
            'department' => 'required',
            'hoofdcategory' => 'required',
            'subcategory' => 'required',
            'body' => 'required',
            'user_id' => 'required',
            'starttijd' => 'required',
        ]);


        $startTime = Carbon::parse($request->starttijd);
        $finishTime = Carbon::now();
        $totalDuration = $finishTime->diffinSeconds($startTime);
        $seconden = $request->starttijd;
        $post = new Post();
        $post->title = $request->title;
        $post->body = $request->body;
        $post->channel_id = $request->channel;
        $post->department_id = $request->department;
        $post->hoofdcategories_id = $request->hoofdcategory;
        $post->subcategories_id = $request->subcategory;
        $post->kennisbankboolean = (int) $request->has('kennisbankboolean');
        $post->feedbackboolean = (int) $request->has('feedbackboolean');
        $post->feedbacktxt = $request->feedbacktxt;
        $post->user_id = $request->user_id;
        $post->seconds = $totalDuration;

        if ($post->save()){
            return redirect()->route('posts.index')
            ->with('flash_message_success', 'Contact,
             ' . $post->title . ' Geregistreerd');
        }else {
            return redirect()->route('posts.index')
            ->with('flash_message_error', 'Contact,
             ' . $post->title . ' NIET Geregistreerd');
        }
        

        //Display a successful message upon save



    }
Snapey
Snapey
4 days ago (993,535 XP)

Is your database table column exactly called kennisbankboolean ?

Cronix
Cronix
4 days ago (727,800 XP)

It looks ok, so I guess same question as Snapey.

I'm also not sure why you need to have a feedbackboolean column at all. If there is feedback, the feedbacktxt field in the db won't be null.

esorone

Hey Both,

Yes, my column is called "kennisbankboolean" and "feedbackboolean". And there is a 0 value stored in the db. I just copy / past the name from sequel Pro to my code editor (just to make sure)

The feedbackboolean service an different purpose. If this one is checked, the feedback is related to a knowledge base. The Feedback field is generic.

I hope you guys got some ideas left. Or maybe a different approach?

esorone

Update.

I just checked the value via js.

<script>
    $(document).ready(function () {
        $('input[name="kennisbankboolean"]').change(function(){ 
        console.log($('.controls').find("input:checkbox[name ='kennisbankboolean']:checked").val());
});
});
</script>

If I check the checkbox, the value is shown as 0 If I uncheck it, i receive "undefined"..

I tried to update the $post with;

      $post->kennisbankboolean = (int) $request->has('kennisbankboolean')? 1 : 0;

Or the other way around, but still no luck.

I would expect a 1 when checked and a 0 unchecked.

Cronix
Cronix
2 days ago (727,800 XP)

The value being sent has nothing to do with it.

This is basic html. If a checkbox is checked, the name and value of the checkbox get submitted in the request. If a checkbox is not checked, it is NOT sent in the request. This has nothing to do with php, javascript or anything else. This is how html forms work for 30 years now.

Of course your javascript is coming up as undefined. The logic in it is flawed. You unchecked it, so find("input:checkbox[name ='kennisbankboolean']:checked") doesn't exist since it's not checked, but you're looking for where it IS checked.

Try a simple example. Put this on your form (don't use that dumb form library)

<input type="checkbox" name="testcb" value="1">Test Checkbox

in the controller, do

public function store(Request $request)
{
    return (int) $request->has('testcb');
    // rest of your code below...doesn't matter for this test
}

Now check the checkbox and submit. You should see a 1. Do the same thing with the checkbox unchecked. You should see a 0.

esorone

Hey Cronix,

I know, the behaviour is at least 30 years, but I cannot solve this one, and my current technique is trail and error.. And read numerous topics online and just try and give some extra input.

You will not believe it, but your solution provides a 0, same as before.

I updated mine:

view
<input type="checkbox" name="kennisbankboolean" value="1">

controller
    $post->kennisbankboolean = (int) $request->has('kennisbankboolean');

I even added your field to my database, contoller, etc

view

<input type="checkbox" name="testcb" value="1">

Controller:
        $post->testcb = (int) $request->has('testcb');

And again only a Zero :-(

What am I missing here........

[Quote] Try a simple example. Put this on your form (don't use that dumb form library) [Unquote]

Done

Cronix
Cronix
2 days ago (727,800 XP)

Do you have anything else interfering with the request, like javascript? I do this all of the time with no issues.

esorone

In the same form I have a "dynamic" cascading pulldown menu. Category and subcategory. I just removed the script, but same result :-(

This one is really giving me an headache

esorone

What I'm going to do, is create a new page tomorrow, Fresh start, and lets see if I'm able to store the proper values.

Keep you guys posted.

Snapey
Snapey
2 days ago (993,535 XP)

dd the actual request data what does your controller recieve?

dd($request->all());
Snapey
Snapey
2 days ago (993,535 XP)

and for your sanity, just hardcode 1 in the controller and check its saved

esorone
esorone
1 day ago (4,160 XP)

Hey Snapey,

I did not see any value during the DD.. $post->kennisbankboolean = (int) $request->has('kennisbankboolean'); $post->feedbackboolean = (int) $request->has('feedbackboolean');

Did not check anything.

array:10 [▼
  "_token" => "iYzAPfAzpyXHsAZVHih2Pn63axcJ"
  "title" => "fasdfasdf"
  "channel" => "1"
  "department" => "2"
  "hoofdcategory" => "1"
  "subcategory" => "3"
  "user_id" => "1"
  "starttijd" => "2018-09-18 19:18:29"
  "body" => "fasdfasdfasd"
  "feedbacktxt" => "00"
]

Checked both checkboxes.

array:10 [▼
  "_token" => "iYzAPfAzpyXHsAZVHih2Pn63axcJiFZ"
  "title" => "fasdfasdf"
  "channel" => "1"
  "department" => "2"
  "hoofdcategory" => "1"
  "subcategory" => "3"
  "user_id" => "1"
  "starttijd" => "2018-09-18 19:19:49"
  "body" => "fasdfasdfasd"
  "feedbacktxt" => "11"
]

I'm still able to store a 0 value.. the other value is null... Im really confused.

Cronix
Cronix
1 day ago (727,800 XP)

Something is wrong with your form then if they don't show up in the request and they were checked. Show the whole form, including opening/closing form tags. Also, any javascript that is on this page.

Please sign in or create an account to participate in this conversation.