How to set default values in custom block?
Permalink 2 users found helpfulI've created my first custom block from scratch and everything seems to be working fine, except that I can't get the block to use defaults that I've specified in its db.xml file. For example, when adding the block, I would like certain checkboxes in the block options to be checked by default, a field called "username" to be filled in as "johndoe", etc.
Here is a sample of what the fields in my db.xml look like:
<field name="username" type="C" size="20"> <default value="johndoe" /> </field> <field name="showEmail" type="L"> <unsigned /> <default value="1" /> </field>
I checked the block's table structure in phpMyAdmin and the defaults I specified are showing up there, but I can't figure out how to get the block to reference them. This is an example of my form_setup_html.php (which I'm including in the add.php and edit.php files):
<?php echo $form->label('username', 'Enter A Username'); ?> <?php echo $form->text('username', $username, array('style' => 'width: 180px'));?> <input id="showEmail" name="showEmail" class="ccm-input-checkbox" type="checkbox" value="1"<?php echo ($showEmail?" checked=\"checked\"":"")?>> <?php echo $form->label('showEmail', 'Email'); ?>
Can anyone suggest how I can get these inputs to use the defaults I've specified in db.xml?
Thanks in advance for any help!
This might be overkill, though -- the nice thing about building everything as blocks is you rarely wind up with a huge codebase (thus making minor duplications like this not as big of a deal).
function add() { $table = new BlockRecord($this->btTable); $tableInfo = $table->TableInfo(); $fieldInfo = $tableInfo->flds; foreach ($fieldInfo as $name => $field) { if ($field->has_default) { $this->set($name, $field->default_value); } } }
Note that this isn't perfect for all situations. For example, MySQL doesn't allow you to set default values on TEXT fields. Also, if you want use php code for default values (like in one of my addons, I default an email address to the current user's address pulled from their profile), you obviously can't set that in the database either.
This could easily be put into a library so it can be called in one line. Maybe even extending the BlockController (although I don't have time to test out all the options of how to integrate this into C5 right now).
-Jordan
Thanks again for your help.
However, it's pretty easy to do this (just requires some non-DRY logic duplication). Add this to your block's controller:
HTH!
-Jordan