[Pro] How to update Checkbox

Hi,

I have big trouble getting a number of checkboxes to be ticked /to be checked, when I read data from MySql, using Php. I know how to read data from a checkbox and store it, so thats no problem.

What I would like to do is to have like a membership area where people can update their profile, and when they login again, they can see the things they previously ticked off, by seeing the checkbox checked.

How shall the PHP code look like, and in which way shall I implement this in Freeway? Using HTML Markup?

Anyone who got experience with this?
Thank you.


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

You could do this with a combination of the PHP Form Action and some hand-rolled PHP. What you will need to do at the very top of your page is to set a variable named for each checkbox to true or 1 when that box is checked, and either don’t set a variable at all or set it to 0 or false if it’s not checked.

The way I usually model these fields in the database is to make them a tinyint(1) since there’s no native Boolean type in SQL (at least, not in MySQL). In my database framework, a tinyint(1) is mapped transparently to a boolean type for further processing.

So you have the following tinyint(1) columns in your database: foo, bar, and baz. On your page in Freeway, make a separate checkbox control for each one, using the third tab from the left in the Inspector to set the Name property to foo, bar, and baz, respectively.

Then apply the PHP Form Action to your page. This will loop through all the form controls on the page and rewrite them to “play back” their same-name variables. For checkboxes, this means adding a reference to the checkMe() function, which also gets written into the page head.

Now, in the Before HTML section of the Page / HTML Markup dialog, add a reference to your form handler / database handler script, or just enter the script there directly.

In any case, make sure that your script loads all of the database fields into global variables when the page loads, and all of your form fields (like checkboxes) will Just Work.

Here’s an example handler, using MyActiveRecord as the database wrapper.

With this in the top of your page, a properly formatted MySQL database, and the latest version of PHP Form Action added to that page, you should see your inputs updating quite magically.

Walter


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

More about MyActiveRecord here: GitHub - walterdavis/myactiverecord: Fork of MyActiveRecord by Jake Grimley

Walter


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

On Nov 13, 2010, at 11:53 AM, waltd wrote:

More about MyActiveRecord here: GitHub - walterdavis/myactiverecord: Fork of MyActiveRecord by Jake Grimley

I’m a big fan of MAR. I wish more people took advantage of Walter’s
work with MAR, you can do some amazing things with it with a little
effort.

Todd


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

Hi Walter,

This looks really good. I´m very glad for your help. So far I have downloaded the action and added it, updated the database fields to tinyint(1). Now I´m looking on the code for the HTML markup. I will update you later.

Cheers,
Soren


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

If all you are doing is using this Action with some hand-coded PHP, then the critical thing to do when you load your database record is to create a global variable named exactly the same as your checkbox.

So if your checkbox has the Name property set to ‘agree’, then make sure there is a variable in the global scope named $agree. This variable should be either true or false, or 0 or 1, depending on the database record.

If that variable exists before the page loads (so if it is set in the Before HTML section of that page in Freeway) then the code provided by the Action will make it work.

Walter


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

Hi Walter,

Sorry, I can not get it to work. Unfortunately I´m not a PHP guru, and I guess its straight forward to do it. I would really like to use the MyActiveRecord as database wrapper. :slight_smile:

I get a parse error:
Parse error: syntax error, unexpected ‘;’ in /home/web/public_html/test/testdb.php on line 34

Code in the Markup Before :

<?php define('MYACTIVERECORD_CONNECTION_STR', '****'); require_once('../php/MyActiveRecord.php'); // I have uploaded the latest file - path works. $foo = clean($_POST['foo']); $bar = clean($_POST['bar']); $baz = clean($_POST['baz']); class User extends MyActiveRecord{ //this model will "wrap" a database table named exactly 'user' //and having an auto-incrementing primary key named 'id' //extend base model methods here function save(){ //mandatory checkbox $this->validate_existence('foo','Foo must be checked'); return parent::save(); } } $id = (isset($_GET['id'])) ? (int) $_GET['id'] : 0; if($user = MyActiveRecord::FindById('User',$id)){ //welcome back }else{ $user = MyActiveRecord::Create('User'); } //handle updates if(isset($_POST['save'])){ // I have correctly given the button the value "save" and chosen "Submit". $user->populate($_POST); $user->save(); if(false == $user->get_errors()){ header('Location: your_form.php?id=' . $user->id); //clear the POST and show the form again exit; }else{ die(print_r($user->get_errors(),true); //ugly error message for testing <---- line 30 where I get the parse error } } //set global variables extract(get_object_vars($user)); ?>

MySQL:

  • I made a database called “user”, containing “id” - int (5), “foo”,“bar”,“bas” of the type tinyint(1).
  • I have applied the PHP Form Action-Page (latest version).

I´m not sure what I need to change or add in the PHP code, to get it to work

With the following code I can read the DB, but I´m sure the code could be made easier with MyActiveRecord:

<?php //Start session session_start(); //Include database connection details require_once('../php/config.php'); //Array to store validation errors $errmsg_arr = array(); //Validation error flag $errflag = false; //Connect to mysql server $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } $id ="2"; // choose row 2 in DB $query="SELECT * FROM features WHERE id='$id'"; $result=mysql_query($query); $num=mysql_numrows($result); //mysql_close(); $i=0; while ($i < $num) { $foo=mysql_result($result,$i,"foo"); $bar=mysql_result($result,$i,"bar"); $baz=mysql_result($result,$i,"baz"); ++$i; } //Function to sanitize values received from the form. Prevents SQL injection function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } if(isset($_POST['Submit']) && !$errors) { //Sanitize the POST values $foo = clean($_POST['foo']); $bar = clean($_POST['bar']); $baz = clean($_POST['baz']); $qry="UPDATE features SET foo='$foo', bar='$bar', baz='$baz' WHERE id='$id'"; mysql_query($qry); //Check whether the query was successful or not if($result) { session_write_close(); header("location: ../test2/testdb.php"); exit(); } else { die("Query failed"); } } else { session_write_close(); } ?>

I will be very glad if you will help me with MyActiveRecord. I appreciate all your help. Thanks again

Cheers,
Soren


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

I left off a closing parenthesis. Make that line 30 read thus:

die(print_r($user->get_errors(),true));

Walter


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

Hi Walter,

Now the page loads without errors, and if I do the following then it reads the DB, and the checkboxes are marked (I have put in a few values manually by using the mySql admin tool):

$id = “1”;
//$id = (isset($_GET[‘id’])) ? (int) $_GET[‘id’] : 0;

You mentioned it is critical to have global values, so I tried to put in the following:
$foo = “0”;
$bar = “0”;
$baz = “0”;
These values match the names of the Checkbox´s. But I can see in the mySql Admin tool that the changes I do on the webpage are not stored in the DB, when I press “send”.

Do you have an idea what the reason could be?

Thanks again! :slight_smile:


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

Did you add the ID to your form submit code? I may not have stressed
that, and it’s important. In your Form Setup dialog, make sure that
the Action is set to this:

yourformpage.php?id=<?=$id?>

That, along with commenting back out the direct value assignments you
made below, should be it. Oh, and if you’re using my code explicitly,
then make sure that your submit button is named exactly ‘save’.
Otherwise, change the line that reads

if(isset($_POST['save']))

to match the Name property of your submit button (set in the third tab
from the left in the Inspector). If these don’t match, then your form
will never be handled at all, it will just sit there like a pudding,
always loading the defaults.

The way this form process works is as follows:

  1. The page loads initially without an ID set for the record. This
    causes the handler to conjure up a blank object with
    MyActiveRecord::Create(‘YourModel’).

  2. extract(get_object_vars($yourModel)) loops through all of the
    properties of that blank object and creates global variables for each
    property.

  3. Your Freeway HTML/PHP loads, using those global variables to fill
    in the blanks. (They’re all set to whatever the default value is for
    each column in the database.)

So that gets you to the point where the user sees the form for the
first time. Now let’s say the user has filled everything in.

  1. The form is submitted to itself. The form handler receives the ID
    in the URL (the GET), and the rest of the form body in the POST.
    Because this is the first submit, the ID is set to 0.

  2. The form handler conjures up another blank object. (The first one
    was never saved, so you’re not adding records without values to your
    database when you load the empty page for the first fill-in – you’re
    just using the “idea” of the object as a template.) This time, it uses
    $yourModel->populate($_POST); to fill in all of the values.

  3. When the handler calls save(), it invokes the save method in your
    model, so if you created some required variables and the user did not
    fill those in, you would find that save would fail, setting an error
    on the model which you could extract using get_errors(). If there are
    no errors, the handler redirects you back to the form page, but this
    time sets the $id variable to the actual ID of the just-created
    record. When the id is real, then the form loads with whatever the
    database knows about that real record.

If the form submission fails, and there are one or more errors, then
the form handler “falls through” to the form itself. (Well, it would
if we took the die() statement out of the sample code and replaced it
with something that could make a nice human-readable error message.)
In this case, the record is not saved, but all of the values that the
user just submitted are still there in the object, waiting to be
extracted into the global space. This gives the user back everything
that she entered, so that the errors can be corrected without the use
of the Back button or having to re-enter anything that was entered
correctly.

Walter

On Nov 16, 2010, at 1:39 AM, Soren F wrote:

Hi Walter,

Now the page loads without errors, and if I do the following then it
reads the DB, and the checkboxes are marked (I have put in a few
values manually by using the mySql admin tool):

$id = “1”;
//$id = (isset($_GET[‘id’])) ? (int) $_GET[‘id’] : 0;

You mentioned it is critical to have global values, so I tried to
put in the following:
$foo = “0”;
$bar = “0”;
$baz = “0”;
These values match the names of the Checkbox´s. But I can see in the
mySql Admin tool that the changes I do on the webpage are not stored
in the DB, when I press “send”.

Do you have an idea what the reason could be?

Thanks again! :slight_smile:


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

Here’s an example Freeway document with the entire thing configured
and ready to go.

http://scripty.walterdavisstudio.com/MAR-demo.zip

When you unzip that file, look in the Media folder for a file called
setup.php. Open this file in a text editor, and update the database
connection details to point to your database server.

Then open the Freeway document and look at the SETUP page there. This
has a blob of SQL to generate the “widgets” table needed to work with
this example document.

Once you have run that SQL on your database server, and uploaded the
Freeway document somewhere on your Web server (maybe make a “widgets”
folder), browsing to the site will show you an empty list of Widgets,
and a link to add one. The form works precisely the way I’ve outlined
previously in this thread, and shows error messages if you don’t
complete all of the fields.

In contrast with the examples I’ve shown here (which work fine on one
page at a time) I extracted the class definition out to the setup.php
file because I was going to use that over again on two different
pages. That’s always a good idea, and it allows you to push more of
the code out to a text file, where you can use a good editor instead
of the Freeway HTML Markup dialog, which is little more than a textarea.

Walter

On Nov 16, 2010, at 1:39 AM, Soren F wrote:

Hi Walter,

Now the page loads without errors, and if I do the following then it
reads the DB, and the checkboxes are marked (I have put in a few
values manually by using the mySql admin tool):

$id = “1”;
//$id = (isset($_GET[‘id’])) ? (int) $_GET[‘id’] : 0;

You mentioned it is critical to have global values, so I tried to
put in the following:
$foo = “0”;
$bar = “0”;
$baz = “0”;
These values match the names of the Checkbox´s. But I can see in the
mySql Admin tool that the changes I do on the webpage are not stored
in the DB, when I press “send”.

Do you have an idea what the reason could be?

Thanks again! :slight_smile:


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

Hi Walter,

Thank you very much! It works great! And its easy to see how the code and setup of the page shall be done.

At the same time, I have learned how to use the CrowBar. Thats a very great action. Its so easy to setup code at any part of the page now.

And the upload stuff action is easy to upload files with.

I have learned a lot today, thanks to you!

Best regards,
Soren


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

You’re very welcome.

Walter

On Nov 17, 2010, at 11:16 PM, Soren F wrote:

Hi Walter,

Thank you very much! It works great! And its easy to see how the
code and setup of the page shall be done.

At the same time, I have learned how to use the CrowBar. Thats a
very great action. Its so easy to setup code at any part of the page
now.

And the upload stuff action is easy to upload files with.

I have learned a lot today, thanks to you!

Best regards,
Soren


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options