Creating Smart Buttons in Agile Toolkit

Monday, October 17th, 2011|Uncategorized|by Romans

I am working on a project, which features numerous places where it’s possible to select a client from a drop-down. I thought about creating a single class, which will work as a button, but would also contain the logic of actually adding the client through a form in jQuery UI Frame.

As a result, I’ve created a universal “NewEntry” button, which can be added anywhere like this.

[php]
$client=$form->addField(‘autocomplete’,'client_id’);
$client->setModel(‘Client’);
$client->add(‘Button_NewEntry’,null,’after_field’)
->setLabel(‘New Client’)->setModel(‘Client’,array(‘name’));
[/php]

This produces the following:

  • Button is added next to the field
  • When button is clicked, new dialog is displayed offering to add new client
  • After form is submitted, dialog closes and new client is automatically selected in auto-complete field
  • Works with any model, label and list of visible fields can be customized

Adding New Button Code

This should be as simple as copy-pasting the following code into your lib/Button/NewEntry.php

[php]
class Button_NewEntry extends Button {
public $field=null;
public $label=null;
public $model=null;
public $fields=null;
public $form=null;
function setText($t){
$this->label=$t;
return parent::setText($t);
}
function setModel($m,$fields=null){
if(is_null($this->label))
throw $this->exception(‘Execute setLabel() before setModel() on this button’);
$this->model=$m;
$this->fields=$fields;
if($this->owner instanceof Form_Field){
$this->field=$this->owner;
}
if($_GET[$this->name]==’click’)return $this->dialog();
if($this->isClicked()){
$this->js()->univ()->dialogURL($this->label,
$this->api->getDestinationURL(null,array(
$this->name=>’click’))
)->execute();
}
}
function dialog(){
$this->api->stickyGET($this->name);
$v=$this->owner->add(‘View’,$this->short_name.’_dlg’,$this->spot);
$_GET['cut_object']=$v->name;
$this->form=$form=$v->add(‘MVCForm’);
$form->setModel($this->model,$this->fields);
if($form->isSubmitted()){
$m=$form->update();
$js=$form->js()->univ()
->closeDialog();
if($this->field){
$js
->getjQuery()
->closest(‘.atk-form’)
->atk4_form(‘setFieldValue’,$this->field->short_name,$m->get(‘id’))
;
}
$js->execute();
}
}
}
[/php]

See also git repository link for my implementation.

3 Comments

Trevor
Posted October 25, 20113:06 am

Hey Romans – really like the functionality and will definitely have a use for this. Thanks for sharing.

Romans
Posted October 25, 20113:07 am

ha, you’ll like my next post. About to publish.. :)

Martijn
Posted April 26, 20127:34 pm

If you stumbled on this and want to use it in 4.2:

$m=$form->update();

change to: $m = $form -> update() -> model -> id;

->atk4_form(‘setFieldValue’,$this->field->short_name,$m->get(‘id’))

change to: ->atk4_form(‘setFieldValue’,$this->field->short_name,$m)