PHP/Javascript form builder/schema definer - php

I know this sounds very much like "Is there a PHP framework that does my entire job for me?" But bear with me.
Say I want to create a signup form for a camp, and I have a simple data structure in mind --
Person
First name
Last name
Address
Address
Line 1
Line 2
Suburb
Town
etc
Things I have seen that do part but not all of what I want:
PHP form libraries like jFormer and ValidForm (not to mention all the big frameworks): these things let you define the form you want to make using a little bit of PHP -- so you'd say "add text field, add textarea", etc -- but they don't let the user edit the form data structure, nor do they automatically save into a data structure. They're more useful for developers.
Front-end form creators like foxyform, jotform: they let the user edit the form but the backend needs to be done in some other way, and it's not linked up.
Then there's Wordpress Pods CMS, which is almost exactly what I want -- but without the wordpress part.
Ideally, I would like one of two things:
1) A microframework where you define your data schema in some reasonably simple way, like say Json or Yaml -- your basic
Person
First name: Text
Last name: Text
Address: has_one Address
Address
... and so on
And it would take that and create the form you needed and maybe even create the database schema and so forth. You could then get hold of the data objects to iterate over in your code elsewhere (I'm not crazy enough to try and automate that as well... Or maybe I am, but certainly it feels outside the scope of this particular encapsulation).
OR
2) The above, plus a little editor for editing the data schema.
Create data type:
Name: [Person]
Fields:
First name: [Text field]
[+ Add field]
I have had a good look around and haven't found anything that's small and standalone and does just this. Pods CMS is almost exactly what I want, but smaller and cleaner and not tied to Wordpress.
Does such a thing exist? If not -- and I'm straying onto opinion here but I'll take a chance -- does it seem like such a thing should exist? Wouldn't it be nice to just be able to drop such a thing into any application, and either write the schema yourself or allow the user to edit it? It doesn't seem so very difficult, and it would be usable in so many contexts.

I am not quite sure such a detail of personalization exists but let's give it a try:
First you should create your classes:
class Person{
private $first_name;
private $last_name;
private $adress;
public function __construct($data=array(), adress $adress=null){
foreach ($data as $cle => $valeur)
$this->$cle=$valeur;
$this->adress=$adress;
}
public function __get($property){
return $this->$property;
}
public function __set($property,$value)
{
$this->$property=$value;
}
public function all_object_properties() {
return get_object_vars($this);
}
public function all_class_properties(){
return get_class_vars(__CLASS__);
}
}
class Adress{
private $id;
private $line_1;
private $line_2;
private $suburb;
public function __construct($data=array()){
foreach ($data as $cle => $valeur)
$this->$cle=$valeur;
}
public function __get($property){
return $this->$property;
}
public function __set($property,$value)
{
$this->$property=$value;
}
public function all_object_properties() {
return get_object_vars($this);
}
public function all_class_properties(){
return get_class_vars(__CLASS__);
}
public function fill($id){
$connexion=db_connect();
$req=$connexion->prepare("SELECT * FROM adresses WHERE id=:id");
$req->execute(array('id'=>$id));
while ($row = $req->fetch(PDO::FETCH_ASSOC)){
foreach ($row as $cle => $valeur)
$this->$cle=$valeur;
}
return $this;
}
public function save(){
$connexion=db_connect();
$sql1="INSERT INTO adresses (";
$sql2=" VALUES (";
$vars=$this->all_properties();
foreach($vars as $var=>$value){
$sql1.=$var.", ";
$sql2.=":".$var.", ";
}
$sql1=substr($sql1,0,-2).")";
$sql2=substr($sql2,0,-2).")";
$sql=$sql1.$sql2;
$query=$connexion->prepare($sql);
$query->execute($vars);
if($query){
$this->id=$connexion->lastInsertId();
return true;
}else{
return false;
}
}
public function update(){
$connexion=db_connect();
$sql1="UPDATE adresses SET ";
$vars=$this->all_properties();
foreach($vars as $var=>$value){
$sql1.=$var."=".":".$var.", ";
}
$sql1=substr($sql1,0,-2)." WHERE id=:id";
$query=$connexion->prepare($sql1);
$query->execute($vars);
if($query){
return true;
}else{
return false;
}
}
}
Then you want the ability to create a form based on a file like JSON or even XML:
<forms>
<form>
<host>name_of_my_page_where_my_form_is_displayed.php</host>
<method>post</method>
<target>#</method>
<input>
<type>text</type>
<name>first_name</type>
<class>Person</class>
</input>
<input>
<type>text</type>
<name>last_name</type>
<class>Person</class>
</input>
<input>
<type>text</type>
<name>line_1</type>
<class>Adress</class>
</input>
<input>
<type>text</type>
<name>suburb</type>
<class>Adress</class>
</input>
</form>
</forms>
Here you need a function to parse and create the form:
function display_form($xml_file,$page_to_display){
$content=null;
$values=array();
$dom = new DOMDocument;
$dom->load($xml_file);
$forms=$dom->getElementsByTagName("form");
foreach($forms as $form){
$urls = $form->getElementsByTagName( "host" );
$url = $urls->item(0)->nodeValue;
if($url==htmlspecialchars($page_to_display)){
$tp_method = $form->getElementsByTagName( "method" );
$method = $tp_method->item(0)->nodeValue;
$tp_target = $form->getElementsByTagName( "target" );
$target = $tp_target->item(0)->nodeValue;
$content="<form action=".$target." method=".$method."><br/>";
$inputs=$dom->getElementsByTagName("input");
foreach($inputs as $input){
$tp = $form->getElementsByTagName( "type" );
$type = $tp->item(0)->nodeValue;
$tp = $form->getElementsByTagName( "name" );
$name = $tp->item(0)->nodeValue;
$tp = $form->getElementsByTagName( "class" );
$class = $tp->item(0)->nodeValue;
$content.="<input type=".$type." name=".$name."/><br/>";
$values[]=array("class"=>$class,"name"=>$name);
}
$content.="<input type='submit' value='Submit'/>";
}
}
return array("content"=>$content,"values"=>$values);
}
Finally in your page where the form is displayed:
<?php
$array=display_form("forms.xml",$_SERVER['REQUEST_URI']);
$content=$array['content'];
$values=$array['values'];
$classes=array();
$names=array();
foreach($values as $tab){
$class=$tab['class'];
$name=$tab['name'];
$classes[]=(!in_array($class,$classes)) ? $class : null;
$names[]=$name;
${$class}[]=$name;
}
$form_submitted=true;
foreach($names as $name){
if(!isset($_POST[$name]))
$form_submitted=false;
}
if($form_submitted){
foreach($classes as $name_class){
$var= new $name_class;
foreach(${$name_class} as $value){
$var->__set($value,$_POST[$value]);
}
$var->save();
}
}
echo $content;
In addition, you may want to create a function to fill your xml.
In each classes you can use functions fill() to retrieve data for an object in the database based on their ID, save() to create a new insert in the database, or update() to update an already existent row based on the ID.
There is a lot of improvement which can be done, but the general idea is here.
Feel free to improve it and make yours!

Related

The right architecture of website / web app development

I have a background in Java, lately I learned a the theory behind some web development language, while my back-end language is PHP. In addition, I started to working with CodeIgniter (I'm not sure if it does matter to my question, but anyway).
So, I started to build a simple galleries system - but not sure if the architecture is right (I based on my background in Java, but I don't know if web development is the same).
The galleries system is very standard: user can upload / delete images and galleries, view gallery, view image and view all galleries (in this case the name of the gallery is displayed and thumb of the last added image). there is pagination at the all 'views'.
I created 3 classes, under application/libraries/galleries:
gallery_actions.php:
class Gallery_Actions {
// Nuber of galleries to display in one page
const galleriesPerPage = 4;
public function getGalleries($page) {
$q = .. query ..;
return $this->getObjectGalleryArray($q->result_array());
}
public function getFeatureGallery() {
$gallery = .. query .. ->row_array();
return new Gallery($gallery);
}
public function getPopularGalleries($limit) {
$q = .. query ..;
return $this->getObjectGalleryArray($q->result_array());
}
// Get database galleries array and return object galleries array
private function getObjectGalleryArray($q = array()) {
$galleries = array();
foreach ($q as $gallery) {
$galleries[] = new Gallery($gallery);
}
return $galleries;
}
}
gallery.php:
class Gallery {
// holds gallery info from DB
// int id, varchar(255) name, varchar(255) lastImg, int countImgs
public $config = array();
// Nuber of imgs to display in one page
const imgsPerPage = 12;
// In most cases (maybe at all), gets all config. sometimes only id.
function __construct($params = array()) {
if (count($params) > 0) {
foreach ($params as $key => $val) {
$this->config[$key] = $val;
}
}
}
// Watch inside gallery
public function getGallery($page) {
return array[
'info' => $this->config,
'images' => $this->getImagesOfGallery($page)
];
}
// Watch when browse galleries
public function getPreview() {
return array[
'name' => $this->config['name'],
'lastImg' => new Gallery_Image($this->config['lastImg']),
'url' => $this->config['url']
];
}
private function getImagesOfGallery($page) {
$q = .. query ..;
$imgs = array();
foreach ($q->result_array() as $img) {
$imgs = new Gallery_Image($img);
}
return $imgs;
}
public function create() { .. }
public function uploadImages() { .. }
public function delete() { .. }
private function updateCount() { .. }
}
Gallery_Image:
class Gallery_Image {
// holds img info from DB
// int id, varchar(255) name, varchar(255) url
public $config;
// In most cases gets all config OR only id.
function __construct($params) {
if (count($params) > 0) {
foreach ($params as $key => $val) {
$this->config[$key] = $val;
}
}
}
public function getImage() { return $this->config; }
public function update() { .. }
public function delete() { .. }
public function getThumb() { .. return url string .. }
}
It's a little long, but it's really not hard to understand.
To be honest, I wrote the code just now, so maybe there are syntax errors - but that not the point.
The point is the mixing of the OOP at the code && web development. The big advantages of this code is that there isn't duplicated code, very clearly, actualize the idea of OO.
WHAT I'M NOT SURE - is the creation of the objects necessary and effective? I mean, web development is the same architecture method such as, for example, building a game for android phone? each table in the database (of course not binding tables etc) has a php class and object?
The web is a delivery mechanism, nothing more. See: http://www.youtube.com/watch?v=WpkDN78P884
As you said, building a game for android and building a web application often have similar architectural challenges. There is no architectural silver bullet - the form and intent of your code should inform each other.
The creation of objects is never necessary - some programmers would prefer to write web apps in assembly! However, objects can be a valuable abstraction. As you said, "The big advantages of this code is that there isn't duplicated code, very clearly, actualize the idea of OO." The important advantages are code readability and maintainability, which are both (almost totally) subjective. It is up to you as the maintainer of the codebase to decide what is most effective for you.
Now, if you are looking for web app architecture OPINIONS, check this out: http://12factor.net/

zf2 forms and object binding, without clearing non-passed values

I've read through the tutorials/reference of the Form-Component in Zend-Framework 2 and maybe I missed it somehow, so I'm asking here.
I've got an object called Node and bound it to a form. I'm using the Zend\Stdlib\Hydrator\ArraySerializable-Standard-Hydrator. So my Node-object has got the two methods of exchangeArray() and getArrayCopy() like this:
class Node
{
public function exchangeArray($data)
{
// Standard-Felder
$this->node_id = (isset($data['node_id'])) ? $data['node_id'] : null;
$this->node_name = (isset($data['node_name'])) ? $data['node_name'] : null;
$this->node_body = (isset($data['node_body'])) ? $data['node_body'] : null;
$this->node_date = (isset($data['node_date'])) ? $data['node_date'] : null;
$this->node_image = (isset($data['node_image'])) ? $data['node_image'] : null;
$this->node_public = (isset($data['node_public'])) ? $data['node_public'] : null;
$this->node_type = (isset($data['node_type'])) ? $data['node_type']:null;
$this->node_route = (isset($data['node_route'])) ? $data['node_route']:null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}
In my Controller I've got an editAction(). There I want to modify the values of this Node-object. So I am using the bind-method of my form. My form has only fields to modify the node_name and the node_body-property. After validating the form and dumping the Node-object after submission of the form the node_name and node_body-properties now contain the values from the submitted form. However all other fields are empty now, even if they contained initial values before.
class AdminController extends AbstractActionController
{
public function editAction()
{
// ... more stuff here (getting Node, etc)
// Get Form
$form = $this->_getForm(); // return a \Zend\Form instance
$form->bind($node); // This is the Node-Object; It contains values for every property
if(true === $this->request->isPost())
{
$data = $this->request->getPost();
$form->setData($data);
// Check if form is valid
if(true === $form->isValid())
{
// Dumping here....
// Here the Node-object only contains values for node_name and node_body all other properties are empty
echo'<pre>';print_r($node);echo'</pre>';exit;
}
}
// View
return array(
'form' => $form,
'node' => $node,
'nodetype' => $nodetype
);
}
}
I want to only overwrite the values which are coming from the form (node_name and node_body) not the other ones. They should remain untouched.
I think a possible solution would be to give the other properties as hidden fields into the form, however I don't wanna do this.
Is there any possibility to not overwrite values which are not present within the form?
I rechecked the code of \Zend\Form and I gotta be honest I just guessed how I can fix my issue.
The only thing I changed is the Hydrator. It seems that the Zend\Stdlib\Hydrator\ArraySerializable is not intended for my case. Since my Node-Object is an object and not an Array I checked the other available hydrators. I've found the Zend\Stdlib\Hydrator\ObjectProperty-hydrator. It works perfectly. Only fields which are available within the form are populated within the bound object. This is exactly what I need. It seems like the ArraySerializable-hydrator resets the object-properties, because it calls the exchangeArray-method of the bound object (Node). And in this method I'm setting the non-given fields to null (see code in my question). Another way would propably be to change the exchangeArray-method, so that it only sets values if they are not available yet.
So the solution in the code is simple:
$form = $this->_getForm();
$form->setHydrator(new \Zend\Stdlib\Hydrator\ObjectProperty()); // Change default hydrator
There is a bug in the class form.php, the filters are not initialized in the bindvalues method just add the line $filter->setData($this->data);
it should look like this after including the line
public function bindValues(array $values = array())
{
if (!is_object($this->object)) {
return;
}
if (!$this->hasValidated() && !empty($values)) {
$this->setData($values);
if (!$this->isValid()) {
return;
}
} elseif (!$this->isValid) {
return;
}
$filter = $this->getInputFilter();
$filter->setData($this->data); //added to fix binding empty data
switch ($this->bindAs) {
case FormInterface::VALUES_RAW:
$data = $filter->getRawValues();
break;
case FormInterface::VALUES_NORMALIZED:
default:
$data = $filter->getValues();
break;
}
$data = $this->prepareBindData($data, $this->data);
// If there is a base fieldset, only hydrate beginning from the base fieldset
if ($this->baseFieldset !== null) {
$data = $data[$this->baseFieldset->getName()];
$this->object = $this->baseFieldset->bindValues($data);
} else {
$this->object = parent::bindValues($data);
}
}
to be precious it is line no 282 in my zf2.0.6 library
this would fix your problem, this happen only for binded object situation
I ran into the same problem, but the solution of Raj is not the right way. This is not a bug as for today the code remains still similar without the 'fix' of Raj, adding the line:
$filter->setData($this->data);
The main problem here is when you bind an object to the form, the inputfilter is not stored inside the Form object. But called every time from the binded object.
public function getInputFilter()
...
$this->object->getInputFilter();
...
}
My problem was that I created every time a new InputFilter object when the function getInputFilter was called. So I corrected this to be something like below:
protected $filter;
...
public function getInputFilter {
if (!isset($this->filter)) {
$this->filter = new InputFilter();
...
}
return $this->filter;
}
I ran into the same issue today but the fix Raj suggested did not work. I am using the latest version of ZF2 (as of this writing) so I am not totally surprised that it didn't work.
Changing to another Hydrator was not possible as my properties are held in an array. Both the ObjectProperty and ClassMethods hydrators rely on your properties actually being declared (ObjectProperty uses object_get_vars and ClassMethods uses property_exists). I didn't want to create my own Hydrator (lazy!).
Instead I stuck with the ArraySerializable hydrator and altered my exchangeArray() method slightly.
Originally I had:
public function exchangeArray(array $data)
{
$newData = [];
foreach($data as $property=>$value)
{
if($this->has($property))
{
$newData[$property] = $value;
}
}
$this->data = $newData;
}
This works fine most of the time, but as you can see it blows away any existing data in $this->data.
I tweaked it as follows:
public function exchangeArray(array $data)
{
$newData = [];
foreach($data as $property=>$value)
{
if($this->has($property))
{
$newData[$property] = $value;
}
}
//$this->data = $newData; I changed this line...
//to...
$this->data = array_merge($this->data, $newData);
}
This preserves any existing keys in $this->data if they are missing from the new data coming in. The only downside to this approach is I can no longer use exchangeArray() to overwrite everything held in $this->data. In my project this approach is a one-off so it is not a big problem. Besides, a new replaceAllData() or overwrite() method is probably preferred in any case, if for no other reason than being obvious what it does.

Is there a way to add a group of elements to a form?

I'm wondering if there was a way to add a group of elements to a zend form as if they were one element, I guess much like a subform, but it seems the functionality of a subform may be too much...
Here's my use-case. I've created a class that handles multi-page forms. I want to be able to write logic to change the buttons at the bottom of the form based on the page of the form I'm on.
I originally thought that Zend-Form-DisplayGroup would fix my problem, but you have to add the items to the form first and then add them to the display group and can't pass a display group through a function with attached elements. I would like to have a function that would be something like
public function setSubmitButtonGroup($submitButtonGroupElements)
{
/*Code to set button group*/
}
The idea of using an array of elements just hit me right now as opposed to something else and add logic to add that array of elements to the form on render... but does anyone have any "better" ideas or done this before?
BTW, if anyone is wondering... I'm loosely basing my initial design off of this section: Zend Framework Advance Form Usage.
Not sure I understand your problem correctly but this how I do some things.
In a Zend_Form object you can add elements as a group with `addElements($elements) in an array. For the Submit button etc. I have a class where I get the $elements array from and then I simply pop it in. I also add a displayGroup but separately and simply to control where the buttons are. Because a form is an object you can do simple things like the following but I always add a reference to show my intent.
update: shuffled the button manipulation
function addButtons(&$form,$nextName = null) {
$buttons = $this->getButtons(); // this will be an array with your buttons
// make sure you have the element names in your buttons arrays
if ( is_string($nextName) ) {
$buttons['nextButton']->setLabel($nextName);
} elseif ( is_bool($nextName) && false === $nextName ) {
unset($buttons['nextButton'];
}
// repeat for other buttons
$form->addElements($buttons);
$elementNames = array_keys($buttons);
$form->addDisplayGroup($elementNames,'buttonGroup',array('legend'=>'Click some buttons'));
}
$this->addButtons($form,'Finish');
You could make yourself a factory that receive three params, your form element, the current controller and the current action. Then in that factory, you could call a builder based on the controller/action combination and you pass your form.
In your builder you add 1, 2 or 3 buttons based on the corresponding controller/action requirement which are stored in diffrent components. Once it is done, you return your form to the factory and the factory return the form.
My_Form // your Zend_Form object
My_Form_Factory // Your new factory (see below)
My_Form_Factory_Builder_Controller_Action // One of your builder (see below)
My_Form_Factory_Component // Extends the corresponding Zend_Form_Elements
// basic factory that can be called like My_Factory::factory($form, $controller, $action)
class My_Form_Factory {
static public function factory($form, $controller, $action)
$builderClass = "My_Form_Factory_Builder_" . $controller . '_' . $action;
$builder = new $builderClass($form);
return $builder->buildForm();
}
// Basic builder
class My_Form_Factory_Builder_Controller_Action
{
protected $_form;
protected $_previousComponent ;
protected $_nextComponent ;
protected $_cancelComponent ;
public function __construct($form)
{
$this->_form = $form;
$this->_previousComponent = new My_Form_Factory_Component_Previous();
$this->_nextComponent = new My_Form_Factory_Component_Next();
$this->_cancelComponent = new My_Form_Factory_Component_Cancel();
}
public function buildForm()
{
$this->_form->addElement($previousCompnent);
$this->_form->addElement($nextComponent);
$this->_form->addElement($cancelComponent);
return $this->_form;
}
}
If you want to automatize the instanciation you could initialize all the different compoments you might require in an abstract class and in the method buildForm() only add the elements you need for that current interface. (I would rather repeat the code in each builder than rely on this kind of "magic" but it a viable method to do it).
So the complexity of my problem comes with knowing what page of the multipage form. Using an array and the above mentioned addElements() helped.
Simple Answer
The answer to my problem was an array that could be manipulated after the form was "built" so to speak but before it was rendered so that I could add to the form using addElements().
Long Answer
To get the whole picture, imagine each time you hit the next or previous button, you are traversing through an array of subforms. In this case one would need a function to handle the button rendering. I ended up using a case statment, though it's not the best implementation in the world (not reusable in the parent class Form_MultiPage), but it worked:
in my extention of my mulipage form class I have
public function setSubmitControls()
{
$previous = new Zend_Form_Element_Submit('previous',array(
'label'=>'previous',
'required'=>false,
'ignore'=>false,
'order'=>9000
));
$cancel = new Zend_Form_Element_Submit('cancel',array(
'label'=>'Cancel',
'required'=>false,
'ignore'=>false,
'order'=>9003
));
$next = new Zend_Form_Element_Submit('next',array(
'label'=>'Next',
'required'=>false,
'ignore'=>false,
'order'=>9002
));
$finished = new Zend_Form_Element_submit('finish',array(
'label'=>'Finish',
'required'=>false,
'ignore'=>false,
'order'=>9004
));
$submitControls = array();
echo var_dump($this->getCurrentSubForm()->getName());
switch($this->getCurrentSubForm()->getName())
{
case 'billInfo':
$submitControls = array(
$next,
$cancel
);
break;
case 'payerInfo':
$submitControls = array(
$previous,
$next,
$cancel
);
break;
//So on for other subforms
}
$this->setSubmitButtonGroup($submitControls);
}
In my parent class, Form_Multipage, I have
public function setSubmitButtonGroup(array $elements)
{
$this->_submitButton = $elements;
}
And
public function addSubmitButtonGroupToSubForm(Zend_Form_SubForm $subForm)
{
$subForm->addElements($this->_submitButton);
return $subForm;
}
Which is called when I render the "page" of the form with this function
public function prepareSubForm($spec)
{
if (is_string($spec)) {
$subForm = $this->{$spec};
} elseif ($spec instanceof Zend_Form_SubForm) {
$subForm = $spec;
} else {
throw new Exception('Invalid argument passed to ' .
__FUNCTION__ . '()');
}
$subform = $this->setSubFormDecorators($subForm);
$subform = $this->addSubmitButtonGroupToSubForm($subForm);
$subform = $this->addSubFormActions($subForm);
$subform->setMethod($this->getMethod());
return $subForm;
}

Implementing not automatic badges with PHP and MYSQL

I have users' table users, where I store information like post_count and so on. I want to have ~50 badges and it is going to be even more than that in future.
So, I want to have a page where member of website could go and take the badge, not automatically give him it like in SO. And after he clicks a button called smth like "Take 'Made 10 posts' badge" the system checks if he has posted 10 posts and doesn't have this badge already, and if it's ok, give him the badge and insert into the new table the badge's id and user_id that member couldn't take it twice.
But I have so many badges, so do I really need to put so many if's to check for all badges? What would be your suggestion on this? How can I make it more optimal if it's even possible?
Thank you.
optimal would be IMHO the the following:
have an object for the user with functions that return user specific attributes/metrics that you initialise with the proper user id (you probably wanna make this a singleton/static for some elements...):
<?
class User {
public function initUser($id) {
/* initialise the user. maby load all metrics now, or if they
are intensive on demand when the functions are called.
you can cache them in a class variable*/
}
public function getPostCount() {
// return number of posts
}
public function getRegisterDate() {
// return register date
}
public function getNumberOfLogins() {
// return the number of logins the user has made over time
}
}
?>
have a badge object that is initialised with an id/key and loads dependencies from your database:
<?
class Badge {
protected $dependencies = array();
public function initBadge($id) {
$this->loadDependencies($id);
}
protected function loadDependencies() {
// load data from mysql and store it into dependencies like so:
$dependencies = array(array(
'value' => 300,
'type' => 'PostCount',
'compare => 'greater',
),...);
$this->dependencies = $dependencies;
}
public function getDependencies() {
return $this->dependencies;
}
}
?>
then you could have a class that controls the awarding of batches (you can also do it inside user...)
and checks dependencies and prints failed dependencies etc...
<?
class BadgeAwarder {
protected $badge = null;
protected $user = null;
public function awardBadge($userid,$badge) {
if(is_null($this->badge)) {
$this->badge = new Badge; // or something else for strange freaky badges, passed by $badge
}
$this->badge->initBadge($badge);
if(is_null($this->user)) {
$this->user = new User;
$this->user->initUser($userid);
}
$allowed = $this->checkDependencies();
if($allowed === true) {
// grant badge, print congratulations
} else if(is_array($failed)) {
// sorry, you failed tu full fill thef ollowing dependencies: print_r($failed);
} else {
echo "error?";
}
}
protected function checkDependencies() {
$failed = array();
foreach($this->badge->getDependencies() as $depdency) {
$value = call_user_func(array($this->badge, 'get'.$depdency['type']));
if(!$this->compare($value,$depdency['value'],$dependency['compare'])) {
$failed[] = $dependency;
}
}
if(count($failed) > 0) {
return $failed;
} else {
return true;
}
}
protected function compare($val1,$val2,$operator) {
if($operator == 'greater') {
return ($val1 > $val2);
}
}
}
?>
you can extend to this class if you have very custom batches that require weird calculations.
hope i brought you on the right track.
untested andp robably full of syntax errors.
welcome to the world of object oriented programming. still wanna do this?
Maybe throw the information into a table and check against that? If it's based on the number of posts, have fields for badge_name and post_count and check that way?

Best ways to handle Record Form in Zend Framework

Once you're OK with basic record form built after example from Tutorial, you realize you want more professionally designed Record Form. E.g. I don't want to duplicate record form for the same table in User and Admin areas.
1) Does anyone use some mechanism, possibly inheritance, to reduce duplication of almost similar admin and user forms? Is that burdensome or sometimes you better just do with copy-pasting?
2) Has anyone considered it to be a good idea to build some basic Record class
that can determine that among several record forms on this page, the current post is addressed specifically to this record form
that can distinguish between Edit or Delete buttons clicks in some organized fashion.
3) My current practice includes putting all form config code (decorators, validations, initial values) into constructor and form submit handling is put into a separate ProcessSubmit() method to free controller of needless code.
All the above addresses to some expected Record Form functionality and I wonder if there is any guideline, good sample app for such slightly more advanced record handling or people are still reinveting the wheel. Wondering how far you should go and where you should stop with such impovements...
Couple of suggestions:
First of all - Use the init() function instead of constructors to add your elements when you are subclassing the form. The init() function happens after the parameters you pass to the class are set.
Second - Instead of subclassing your form - you can just set an "option" to enable the admin stuff:
class My_Record_Form extends Zend_Form {
protected $_record = null;
public function setRecord($record) {
$this->_record = $record;
}
public function getRecord() {
if ($this->_record === null || (!$this->_record instanceOf My_Record)) {
throw new Exception("Record not set - or not the right type");
}
return $this->_record;
}
protected $_admin = false;
public function setAdmin($admin) {
$this->_admin = $admin;
}
public function getAdmin() { return $this->_admin; }
public function init() {
$record = $this->getRecord();
$this->addElement(......);
$this->addElement(......);
$this->addElement(......);
if ($this->getAdmin()) {
$this->addElement(.....);
}
$this->setDefaults($record->toArray());
}
public function process(array $data) {
if ($this->isValid($data)) {
$record = $this->getRecord();
if (isset($this->delete) && $this->delete->getValue()) {
// delete button was clicked
$record->delete();
return true;
}
$record->setFromArray($this->getValues());
$record->save();
return true;
}
}
}
Then in your controller you can do something like:
$form = new My_Record_Form(array(
'record'=>$record,
'admin'=>My_Auth::getInstance()->hasPermission($record, 'admin')
));
There is nothing "wrong" with making a My_Record_Admin_Form that handles the admin stuff as well - but I found this method keeps all the "record form" code in one single place, and a bit easier to maintain.
To answer section 2: The edit forms in my code are returned from a function of the model: $record->getEditForm() The controller code ends up looking a little like this:
protected $_domain = null;
protected function _getDomain($allowNew = false)
{
if ($this->_domain)
{
return $this->view->domain = $this->_domain;
} else {
$id = $this->_request->getParam('id');
if (($id == 'new' || $id=='') && $allowNew)
{
MW_Auth::getInstance()->requirePrivilege($this->_table, 'create');
$domain = $this->_table->createRow();
} else {
$domain = $this->_table->find($id)->current();
if (!$domain) throw new MW_Controller_404Exception('Domain not found');
}
return $this->view->domain = $this->_domain = $domain;
}
}
public function editAction()
{
$domain = $this->_getDomain(true);
MW_Auth::getInstance()->requirePrivilege($domain,'edit');
$form = $domain->getEditForm();
if ($this->_request->isPost() && $form->process($this->_request->getPost()))
{
if ($form->delete && $form->delete->getValue())
{
return $this->_redirect($this->view->url(array(
'controller'=>'domain',
'action'=>'index',
), null, true));
} else {
return $this->_redirect($this->view->url(array(
'controller'=>'domain',
'action'=>'view',
'id'=>$form->getDomain()->id,
), null, true));
}
}
$this->view->form = $form;
}
So - the actual id of the record is passed in the URI /domain/edit/id/10 for instance. If you were to put multiple of these forms on a page - you should make sure to set the "action" attribute of the form to point to an action specific to that form.
I created a SimpleTable extends Zend_Db_Table and SimpleForm extends Zend_Db_Form classes. Both of these assume that your table has an auto-incrementing ID column.
SimpleTable has a saveForm(SimpleForm $form) function which uses the dynamic binding to match form element names to the columns of the record. I also included an overridable saveFormCustom($form) for any special handling.
The SimpleForm has an abstract setup() which must be overridden to setup the form. I use the init() to do the initial setup (such as adding the hidden ID field).
However, to be honest, I really don't like using the Zend_Form object, I feel like that should be handled in the View, not the Model or Controller.

Categories