sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function cutRender() { $x = $this->app->template->get('document_ready'); if (is_array($x)) { $x = implode('', $x); } if (!empty($x)) { echo '<script type="text/javascript">'.$x.'</script>'; } }
[private] When partial render is done, this function includes JS for rendered region.
entailment
public function getJS($obj) { $this->hook('pre-getJS'); $r = ''; foreach ($obj->js as $key => $chains) { $o = ''; foreach ($chains as $chain) { $o .= $chain->_render().";\n"; } switch ($key) { case 'never': // send into debug output //$s = "if(console)console.log(". // "'Element','".$obj->name."','no action:','".str_replace("\n",'',addslashes($o))."')" //if(strlen($o)>2) $this->addOnReady($s); continue; case 'always': $r .= $o; break; default: $o = ''; foreach ($chains as $chain) { $o .= $chain->_enclose($key)->_render().";\n"; } $r .= $o; } } if ($r) { $this->addOnReady($r); } return $r; }
[private] Collect JavaScript chains from specified object and add them into onReady section. @param AbstractView $obj @return string
entailment
protected function buildCall($url) { if (!$this->callBuilt) { $this->apiBase .= $url; $this->callBuilt = true; } }
Builds the API call address. @param $url
entailment
protected function buildUrl(array $segments = []) { //Get the base URL and add a ? $url = $this->apiBase.'?'; if (isset($this->apiEnding)) { $segments = array_merge($segments, $this->apiEnding); } foreach ($segments as $key => $value) { $url = $url."$key=$value&"; } //Remove the final & $url = substr($url, 0, -1); return $url; }
Builds a URL. @param array $segments @return string
entailment
public function buildBody($values, $key = null) { if (is_array($values)) { $this->body = array_merge($this->body, $values); } else { $this->body[$key] = $values; } }
Builds the body part of the request and adds it to the body array. @param array|string $values @param null $key
entailment
protected function getAuth() { if (isset($this->auth['username']) && isset($this->auth['password'])) { return [$this->auth['username'], $this->auth['password']]; } }
Returns the auth array for requests. If not set, will return null. @return array|null
entailment
public function send(OutgoingMessage $message) { $composeMessage = $message->composeMessage(); //Convert to sms77 format. $numbers = implode(',', $message->getTo()); $data = [ 'u' => $this->auth['username'], 'p' => $this->auth['password'], 'to' => $numbers, 'from' => $message->getFrom(), 'type' => 'direct', 'text' => $composeMessage, 'debug' => (int) $this->debug, ]; $this->buildCall(''); $this->buildBody($data); $response = $this->postRequest(); $responseBody = $response->getBody()->read(3); if ($this->hasError($responseBody)) { $this->handleError($responseBody); } return $response; }
Sends a SMS message. @param \SimpleSoftwareIO\SMS\OutgoingMessage $message
entailment
protected function handleError($body) { $error = 'An error occurred. Status code: '.$body.' - '; //From https://www.sms77.de/api.pdf Rückgabewerte (German doc) switch ($body) { case '101': $error .= 'Versand an mindestens einen Empfänger fehlgeschlagen'; break; case '201': $error .= 'Absender ungültig. Erlaubt sind max 11 alphanumerische oder 16 numerische Zeichen.'; break; case '202': $error .= 'Empfängernummer ungültig'; break; case '300': $error .= 'Bitte Benutzer/Passwort angeben'; break; case '301': $error .= 'Variable to nicht gesetzt'; break; case '304': $error .= 'Variable type nicht gesetzt'; break; case '305': $error .= 'Variable text nicht gesetzt'; break; case '306': $error .= 'Absendernummer ungültig (nur bei Standard SMS). Diese muss vom Format 0049... sein un eine gültige Handynummer darstellen.'; break; case '307': $error .= 'Variable url nicht gesetzt'; break; case '400': $error .= 'type ungültig. Siehe erlaubte Werte oben.'; break; case '401': $error .= 'Variable text ist zu lang'; break; case '402': $error .= 'Reloadsperre – diese SMS wurde bereits innerhalb der letzten 90 Sekunden verschickt'; break; case '500': $error .= 'Zu wenig Guthaben vorhanden.'; break; case '600': $error .= 'Carrier Zustellung misslungen'; break; case '700': $error .= 'Unbekannter Fehler'; break; case '801': $error .= 'Logodatei nicht angegeben'; break; case '802': $error .= 'Logodatei existiert nicht'; break; case '803': $error .= 'Klingelton nicht angegeben'; break; case '900': $error .= 'Benutzer/Passwort-Kombination falsch'; break; case '902': $error .= 'http API für diesen Account deaktiviert'; break; case '903': $error .= 'Server IP ist falsch'; break; case '11': $error .= 'SMS Carrier temporär nicht verfügbar'; break; } $this->throwNotSentException($error); }
Log the error message which ocurred. @param $body
entailment
public function addTitle($title, $class = 'Menu_Advanced_Title') { $i = $this->add( $class, null, null, array_merge($this->defaultTemplate(), array('Title')) ); /** @type Menu_Advanced_Title $i */ $i->set($title); return $i; }
Adds a title to your menu.
entailment
public function addMenuItem($page, $label = null) { if (!$label) { $label = ucwords(str_replace('_', ' ', $page)); } return $this->addItem($label, $page); }
compatibility
entailment
public function getUploadedFiles() { if ($c = $this->model) { $a = explode(',', $this->value); $b = array(); foreach ($a as $val) { if ($val) { $b[] = $val; } } $files = implode(',', filter_var_array($b, FILTER_VALIDATE_INT)); if ($files) { $c->addCondition('id', 'in', ($files ? $files : 0)); $data = $c->getRows(array( 'id', 'url', 'thumb_url', $this->getOriginalFilenameFieldName(), $this->getFilesizeFieldName() )); } else { $data = array(); } return $this->formatFiles($data); } }
those can be done in flash thingie as well
entailment
public function setTarget($js_func) { $this->on('click', 'a')->univ()->frameURL($this->js()->_selectorThis()->attr('href')); return $this; }
This will add a new behaviour for clicking on the menu items. For example setTarget('frameURL') will show menu links inside a frame instead of just linking to them.
entailment
public function addSubMenu($label) { // we use MenuSeparator tag here just to put View_Popover outside of UL list. // Otherwise it breaks correct HTML and CSS. /** @type View_Popover $f */ $f = $this->add('View_Popover'); $this->addMenuItem($f->showJS('#'.$this->name.'_i'.count($this->items)), $label); return $f->add('Menu_jUI'); }
@param string $label @return Menu_jUI
entailment
public function setModel($model, $display_field = null) { if ($model instanceof Model) { return AbstractObject::setModel($model); } $this->model_name = is_string($model) ? $model : get_class($model); $this->model_name = (string) $this->app->normalizeClassName($this->model_name, 'Model'); if ($display_field) { $this->display_field = (string) $display_field; } if ($display_field !== false) { $this->owner->addExpression($this->getDereferenced()) ->set(array($this, 'calculateSubQuery')) ->caption((string) $this->caption()); } $this->system(true); $this->editable(true); $this->visible(false); return $this; }
Set model @param Model|string $model @param string|bool $display_field @return Model|$this
entailment
public function getModel() { if (!$this->model) { $this->model = $this->add($this->model_name); } /** @type Model $this->model */ if ($this->display_field) { $this->model->title_field = $this->display_field; } if ($this->table_alias) { $this->model->table_alias = $this->table_alias; } return $this->model; }
Return model of field @return Model
entailment
public function ref($mode = null) { if ($mode == 'model') { return $this->add($this->model_name); } $this->getModel()->unload(); if ($mode === false || $mode == 'ignore') { return $this->model; } if ($mode == 'load') { return $this->model->load($this->get()); } if ($mode === null) { if ($this->get()) { $this->model->tryLoad($this->get()); } return $this->model; } if ($mode == 'create') { if ($this->get()) { $this->model->tryLoad($this->get()); } if (!$this->model->loaded()) { $this->model->save(); $this->set($this->model->id); $this->owner->save(); return $this->model; } } if ($mode == 'link') { /** @type Model $m */ $m = $this->add($this->model_name); if ($this->get()) { $m->tryLoad($this->get()); } $t = $this; if (!$m->loaded()) { $m->addHook('afterSave', function ($m) use ($t) { $t->set($m->id); $t->owner->saveLater(); }); } return $m; } }
ref() will traverse reference and will attempt to load related model's entry. If the entry will fail to load it will return model which would not be loaded. This can be changed by specifying an argument:. 'model' - simply create new model and return it without loading anything false or 'ignore' - will not even try to load anything null (default) - will tryLoad() 'load' - will always load the model and if record is not present, will fail 'create' - if record fails to load, will create new record, save, get ID and insert into $this 'link' - if record fails to load, will return new record, with appropriate afterSave hander, which will update current model also and save it too. @param string|bool|null $mode @return Model
entailment
public function refSQL() { /** @type SQL_Model $q */ $q = $this->ref('model'); $q->addCondition($q->id_field, $this); return $q; }
Return DSQL for field @return SQL_Model
entailment
public function getDereferenced() { if ($this->dereferenced_field) { return $this->dereferenced_field; } $f = preg_replace('/_id$/', '', $this->short_name); if ($f != $this->short_name) { return $f; } $f = $this->short_name.'_text'; if ($this->owner->hasElement($f)) { return $f; } $f = $this->_unique($this->owner->elements, $f); $this->dereferenced_field = $f; return $f; }
Return name of dereferenced field @return string
entailment
public function destroy() { if ($e = $this->owner->hasElement($this->getDereferenced())) { $e->destroy(); } return parent::destroy(); }
Destroy this field and dereferenced field. @return $this
entailment
public function init() { parent::init(); $this->add($this->layout_class); $this->menu = $this->layout->addMenu('Menu_Vertical'); $this->menu->swatch = 'ink'; //$m = $this->layout->addFooter('Menu_Horizontal'); //$m->addItem('foobar'); $this->add('jUI'); $this->initSandbox(); }
Initialization.
entailment
public function page_sandbox($p) { $p->title = 'Install Developer Tools'; //$p->addCrumb('Install Developer Tools'); $v = $p->add('View', null, null, array('view/developer-tools')); $v->add('Button')->set('Install Now') ->addClass('atk-swatch-green') ->onClick(function () { $install_dir = getcwd(); if (file_exists($install_dir).'/VERSION') { $install_dir = dirname($install_dir); } $path_d = $install_dir.'/agiletoolkit-sandbox-d.phar'; $path = $install_dir.'/agiletoolkit-sandbox.phar'; $url = 'http://www4.agiletoolkit.org/dist/agiletoolkit-sandbox.phar'; if (file_put_contents($path_d, file_get_contents($url)) === false) { return 'update error'; } else { if (rename($path_d, $path) === false) { // get version of a phar return 'update error'; } else { $version = file_get_contents('phar://'.$path.'/VERSION'); return 'updated to '.$version; } } }); }
@todo Description @return string
entailment
public function getInstalledAddons() { if (!$this->controller_install_addon) { $this->controller_install_addon = $this->add('sandbox\\Controller_InstallAddon'); } if ($this->controller_install_addon && $this->controller_install_addon->getSndBoxAddonReader()) { return $this->controller_install_addon->getSndBoxAddonReader()->getReflections(); } return array(); }
Return all registered in sandbox_addons.json addons sandbox/Controller_AddonsConfig_Reflection. @return array
entailment
public function getInitiatedAddons($addon_api_name = null) { if ($addon_api_name !== null) { return $this->addons[$addon_api_name]; } return $this->addons; }
@todo Description @param string $addon_api_name @return AbstractObject|array Addon object or array of objects
entailment
private function initAddon($addon) { $base_path = $this->pathfinder->base_location->getPath(); $init_class_path = $base_path.'/../'.$addon->get('addon_full_path').'/lib/Initiator.php'; if (file_exists($init_class_path)) { include $init_class_path; $class_name = str_replace('/', '\\', $addon->get('name').'\\Initiator'); /** @type Controller_Addon $init */ $init = $this->add($class_name, array( 'addon_obj' => $addon, 'base_path' => $base_path, )); if (!is_a($init, 'Controller_Addon')) { throw $this->exception( 'Initiator of '.$addon->get('name').' is inherited not from \Controller_Addon' ); } /* * initiators of all addons are accessible * from all around the project * through $this->app->getInitiatedAddons() */ $this->addons[$init->api_var] = $init; if ($init->with_pages) { $init->routePages($init->api_var); } } }
@todo Description @param Controller_Addon $addon
entailment
public function importFields($model, $fields = null) { $this->model = $model; if ($fields === false) { return; } if (!$fields) { if ($model->only_fields) { $fields = $model->only_fields; } else { $fields = []; // get all field-elements foreach ($model->elements as $field => $f_object) { if ($f_object instanceof \atk4\data\Field) { $fields[] = $f_object; } } } } if (!is_array($fields)) { $fields = [$fields]; } // import fields one by one foreach ($fields as $field) { $this->importField($field); } return $this; }
Import model fields in view. Use $fields === false if you want to associate view with model, but don't fill view fields. @param \atk4\data\Model $model @param array|string|bool $fields @return void|$this
entailment
public function importField($field) { if (is_string($field)) { $field = $this->model->hasElement($field); } /** @type \atk4\data\Field $field */ if (!$field || !$field instanceof \atk4\data\Field) { return; } // prepare name $name = $field->short_name; // prepare caption $caption = isset($field->ui['caption']) ? $field->ui['caption'] : ucwords(str_replace('_', ' ', $name)); // prepare value $value = $field->get(); // if value is null, then just set empty string as value in template and break out if ($value === null) { $this->owner->template->setHTML(array($name => '', $name.'-caption' => $caption)); return; } // take care of some special data types switch ($field->type) { case 'boolean': if ($value === true || $value === 1 || $value === 'Y') { $value = '<i class="icon-check">&nbsp;'.$this->app->_('yes').'</i>'; } else { $value = '<i class="icon-check-empty">&nbsp;'.$this->app->_('no').'</i>'; } break; case 'date': $value = $value->format($this->app->getConfig('locale/date', 'Y-m-d')); break; case 'datetime': $value = $value->format($this->app->getConfig('locale/datetime', 'Y-m-d H:i:s')); break; case 'time': $value = $value->format($this->app->getConfig('locale/time', 'H:i:s')); break; default: $value = $this->model->persistence->typecastsaveField($field, $value); } // support valueList if (isset($field->ui['valueList'][$value])) { $value = $field->ui['valueList'][$value]; } // support hasOne if ($ref_field = $this->model->hasRef($name)) { $m = $ref_field->ref(); $value = $m->get($m->title_field); } // fill template $data = array($name => $value, $name.'-caption' => $caption); $this->owner->template->setHTML($data); }
Import one field from model into form. @param string|\atk4\data\Field $field @return void
entailment
public function sendRawRequest($model, $url, $method = 'GET', $data = null) { if ($model->debug) { echo '<font color="blue">'. htmlspecialchars("$method $url (".json_encode($data).')'). '</font>'; } $method = strtolower($method); $pest = $model->_table[$this->short_name]; if ($data) { return $pest->$method($url, $data); } else { return $pest->$method($url); } }
Sends request to specified URL with specified method and data.
entailment
public function loadById($model, $id) { $data = $this->sendItemRequest($model, $id); if (is_array($data)) { $model->id = $id; $model->data = $data; } }
Implement loadBy
entailment
public function save($model, $id, $data) { if (is_null($id)) { // insert $model->data = $this->sendCollectionRequest($model, $this->insert_mode, $data); $model->id = $model->data ? $model->data[$model->id_field] : null; } else { // update $model->data = $this->sendItemRequest($model, $id, $this->update_mode, $data); $model->id = $model->data ? $model->data[$model->id_field] : null; } return $model->id; }
Saving, updating and deleting data
entailment
public function isActive($mode = null) { if ($mode !== null && isset($_GET[$this->name])) { return $_GET[$this->name] == $mode; } return isset($_GET[$this->name]) ? $_GET[$this->name] : false; }
Returns true if the URL is requesting the page to be shown. If no parameter is passed, then return active page mode. @param string $mode Optionally ask for specific mode @return bool|string
entailment
public function bindEvent($title = '', $event = 'click', $selector = null) { $t = $this->type; if (is_null($event)) { $event = 'click'; } $this->owner->on($event, $selector)->univ()->$t($title, $this->getURL(), $this->frame_options); return $this; }
Bind owner's event (click by default) to a JavaScript chain which would open a new frame (or dialog, depending on $type property), and execute associated code inside it. @param string $title Title of the frame @param string $event JavaScript event @param string $selector Not all parent will respond to click but only a selector @return $this
entailment
public function set($method_or_arg, $method = null) { $method = is_callable($method_or_arg) ? $method_or_arg : $method; $arg = is_callable($method_or_arg) ? null : $method_or_arg; $self = $this; if ($this->isActive($arg)) { $this->app->addHook('post-init', function () use ($method, $self) { $page = $self->getPage(); $page->id = $_GET[$self->name.'_id']; $self->app->stickyGET($self->name.'_id'); try { call_user_func($method, $page, $self); } catch (Exception $e) { // post-init cannot catch StopInit if ($e instanceof Exception_StopInit) { return; } throw $e; // exception occured possibly due to a nested page. We // are already executing from post-init, so // it's fine to ignore it. } //Imants: most likely forgetting is not needed, because we stop execution anyway //$self->app->stickyForget($self->name.'_id'); //$self->app->stickyForget($self->name); }); throw $this->exception('', 'StopInit'); } return $this; }
Associates code with the page. This code will be executed within a brand new page when called by URL. @param callable $method_or_arg Optional argument @param callable $method function($page){ .. } @return $this
entailment
public function getPage() { if ($this->page) { return $this->page; } // Remove original page $this->app->page_object->destroy(false); $this->page = $this->app->add( $this->page_class, $this->name, null, $this->page_template ); /** @type Page $this->page */ $this->app->page_object = $this->page; $this->app->stickyGET($this->name); return $this->page; }
Simply returns a page we can put stuff on. This page would be displayed instead of regular page, so beware. @return Page page to be displayed
entailment
public function addColumn($name, $title = null, $buttontext = null, $grid = null) { if ($grid === null) { $grid = $this->owner; } /** @type Grid $this->owner */ /** @type Grid $grid */ if (!is_array($buttontext)) { $buttontext = array('descr' => $buttontext); } if (!$buttontext['descr']) { $buttontext['descr'] = $title ?: ucwords(str_replace('_', ' ', $name)); } $icon = ''; if ($buttontext['icon']) { if ($buttontext['icon'][0] != '<') { $icon .= '<i class="icon-'.$buttontext['icon'].'"></i>'; } else { $icon .= $buttontext['icon']; } $icon .= '&nbsp;'; } $grid->addColumn('template', $name, $buttontext ?: $title); $grid->setTemplate( '<button type="button" class="atk-button-small pb_'.$name.'">'. $icon.$this->app->encodeHtmlChars($buttontext['descr']). '</button>' ); $grid->columns[$name]['thparam'] .= ' style="width: 40px; text-align: center"'; //$grid->js(true)->_selector('#'.$grid->name.' .pb_'.$name)->button(); $t = $this->type; $grid->js('click')->_selector('#'.$grid->name.' .pb_'.$name)->univ() ->$t($title, array($this->getURL($name), $this->name.'_id' => $grid->js()->_selectorThis()->closest('tr')->attr('data-id'), ), $this->frame_options); return $this; }
Call this if you are adding this inside a grid. @param string $name Field Name (must not contain spaces) @param string $title Header for the column @param array|string $buttontext Text to put on the button @param Grid $grid Specify grid to use, other than $owner @return $this
entailment
public function addIcon($i) { /** @type Icon $icon */ $icon = $this->add('Icon', null, 'Icon'); return $icon->set($i)->addClass('atk-size-mega'); }
By default box uses information Icon. You can use addIcon() to override or $this->template->del('Icon') to remove. @param string $i @return Icon
entailment
public function addButton($label = 'Continue') { if (!is_array($label)) { $label = array($label, 'icon-r' => 'right-big'); } /** @type Button $button */ $button = $this->add('Button', null, 'Button'); return $button->set($label); }
Adds Button on the right side of the box for follow-up action. @param array|string $label @return Button
entailment
public function addClose() { if ($this->recall('closed', false)) { $this->destroy(); } $self = $this; /** @type Icon $icon */ $icon = $this->add('Icon', null, 'Button'); $icon ->addComponents(array('size' => 'mega')) ->set('cancel-1') ->addStyle(array('cursor' => 'pointer')) ->on('click', function ($js) use ($self) { $self->memorize('closed', true); return $self->js()->hide()->execute(); }); return $this; }
View box can be closed by clicking on the cross. @return $this
entailment
public function init() { parent::init(); if (!$this->skip_var) { $this->skip_var = $this->name.'_skip'; } $this->skip_var = $this->_shorten($this->skip_var); }
Initialization.
entailment
public function setSource($source) { if ($this->memorize) { if (isset($_GET[$this->skip_var])) { $this->skip = $this->memorize('skip', (int) $_GET[$this->skip_var]); } else { $this->skip = (int) $this->recall('skip'); } } else { $this->skip = @$_GET[$this->skip_var] + 0; } // Start iterating early ($source = DSQL of model) if ($source instanceof SQL_Model) { $source = $source->_preexec(); } if ($source instanceof DB_dsql) { $source->limit($this->ipp, $this->skip); $source->calcFoundRows(); $this->source = $source; } elseif ($source instanceof \atk4\data\Model) { $this->source = $source->setLimit($this->ipp, $this->skip); } elseif ($source instanceof Model) { $this->source = $source->setLimit($this->ipp, $this->skip); } else { // NOTE: no limiting enabled for unknown data source $this->source = &$source; } }
Set a custom source. Must be an object with foundRows() method. @param mixed $source
entailment
public function recursiveRender() { // get data source if (!$this->source) { // force grid sorting implemented in Grid_Advanced if ($this->owner instanceof Grid_Advanced) { $this->owner->getIterator(); } // set data source for Paginator if ($this->owner->model) { $this->setSource($this->owner->model); } elseif ($this->owner->dq) { $this->setSource($this->owner->dq); } else { throw $this->exception('Unable to find source for Paginator'); } } // calculate found rows if ($this->source instanceof DB_dsql) { $this->source->preexec(); $this->found_rows = $this->source->foundRows(); } elseif ($this->source instanceof \atk4\data\Model) { $this->found_rows = (int) $this->source->action('count')->getOne(); } elseif ($this->source instanceof Model) { $this->found_rows = (int) $this->source->count(); } else { $this->found_rows = count($this->source); } // calculate current page and total pages $this->cur_page = (int) floor($this->skip / $this->ipp) + 1; $this->total_pages = (int) ceil($this->found_rows / $this->ipp); if ($this->cur_page > $this->total_pages || ($this->cur_page == 1 && $this->skip != 0)) { $this->cur_page = 1; if ($this->memorize) { $this->memorize('skip', $this->skip = 0); } if ($this->source instanceof DB_dsql) { $this->source->limit($this->ipp, $this->skip); $this->source->rewind(); // re-execute the query } elseif ($this->source instanceof \atk4\data\Model) { $this->source->setLimit($this->ipp, $this->skip); } elseif ($this->source instanceof Model) { $this->source->setLimit($this->ipp, $this->skip); } else { // Imants: not sure if this is correct, but it was like this before $this->source->setLimit($this->ipp, $this->skip); } } // no need for paginator if there is only one page if ($this->total_pages <= 1) { return $this->destroy(); } if ($this->cur_page > 1) { /** @type View $v */ $v = $this->add('View', null, 'prev'); $v->setElement('a') ->setAttr('href', $this->app->url( $this->base_page, $u = array($this->skip_var => $pn = max(0, $this->skip - $this->ipp)) )) ->setAttr('data-skip', $pn) ->set('« Prev') ; } else { $this->template->tryDel('prev'); } if ($this->cur_page < $this->total_pages) { /** @type View $v */ $v = $this->add('View', null, 'next'); $v->setElement('a') ->setAttr('href', $this->app->url( $this->base_page, $u = array($this->skip_var => $pn = $this->skip + $this->ipp) )) ->setAttr('data-skip', $pn) ->set('Next »') ; } else { $this->template->tryDel('next'); } // First page if ($this->cur_page > $this->range + 1) { /** @type View $v */ $v = $this->add('View', null, 'first'); $v->setElement('a') ->setAttr('href', $this->app->url( $this->base_page, $u = array($this->skip_var => $pn = max(0, 0)) )) ->setAttr('data-skip', $pn) ->set('1') ; if ($this->cur_page > $this->range + 2) { /** @type View $v */ $v = $this->add('View', null, 'points_left'); $v->setElement('span') ->set('...') ; } } // Last page if ($this->cur_page < $this->total_pages - $this->range) { /** @type View $v */ $v = $this->add('View', null, 'last'); $v->setElement('a') ->setAttr('href', $this->app->url( $this->base_page, $u = array($this->skip_var => $pn = max(0, ($this->total_pages - 1) * $this->ipp)) )) ->setAttr('data-skip', $pn) ->set($this->total_pages) ; if ($this->cur_page < $this->total_pages - $this->range - 1) { /** @type View $v */ $v = $this->add('View', null, 'points_right'); $v->setElement('span') ->set('...') ; } } // generate source for Paginator Lister (pages, links, labels etc.) $data = array(); //setting cur as array seems not working in atk4.3. String is working $tplcur = $this->template->get('cur'); $tplcur = (isset($tplcur[0])) ? $tplcur[0] : ''; $range = range( max(1, $this->cur_page - $this->range), min($this->total_pages, $this->cur_page + $this->range) ); foreach ($range as $p) { $data[] = array( 'href' => $this->app->url($this->base_page, array($this->skip_var => $pn = ($p - 1) * $this->ipp)), 'pn' => $pn, 'cur' => $p == $this->cur_page ? $tplcur : '', 'label' => $p, ); } if ($this->ajax_reload) { $this->js( 'click', $this->owner->js()->reload( array($this->skip_var => $this->js()->_selectorThis()->attr('data-skip')) ) )->_selector('#'.$this->name.' a'); } parent::setSource($data); return parent::recursiveRender(); }
Recursively render this view.
entailment
public function driver($driver) { $this->container['sms.sender'] = $this->container->share(function ($app) use ($driver) { return (new DriverManager($app))->driver($driver); }); $this->driver = $this->container['sms.sender']; }
Changes the set SMS driver. @param $driver
entailment
public function send($view, $data, $callback) { $data['message'] = $message = $this->createOutgoingMessage(); //We need to set the properties so that we can later pass this onto the Illuminate Mailer class if the e-mail gateway is used. $message->view($view); $message->data($data); call_user_func($callback, $message); $this->driver->send($message); return $message; }
Send a SMS. @param string $view The desired view. @param array $data The data that needs to be passed into the view. @param \Closure $callback The methods that you wish to fun on the message. @return \SimpleSoftwareIO\SMS\OutgoingMessage The outgoing message that was sent.
entailment
protected function createOutgoingMessage() { $message = new OutgoingMessage($this->container['view']); //If a from address is set, pass it along to the message class. if (isset($this->from)) { $message->from($this->from); } return $message; }
Creates a new Message instance. @return \SimpleSoftwareIO\SMS\OutgoingMessage
entailment
public function handle($request, Closure $next) { $request->merge($request->xml(true)); return $next($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
entailment
public function loadCurrent($model) { $model->_table[$this->short_name]->next(); $model->data = $model->_table[$this->short_name]->current(); $model->id = $model->data[$model->id_field]; }
Provided that rewind was called before, load next data entry
entailment
public function count($model, $alias = null) { // prepare new query $q = $this->getDsqlForSelect($model)->del('fields')->del('order')->del('limit'); // add expression field to query return $q->field($q->count(), $alias); }
Returns dynamic query selecting number of entries in the database. @param string $alias Optional alias of count expression @return DSQL
entailment
public function reload() { $f = $this->findTemplate($this->template_file); $template_source = implode('', file($f)); $this->loadTemplateFromString($template_source); return $this; }
Causes the template to be refreshed from it's original source
entailment
public function exception($message = 'Undefined Exception', $type = null, $code = null) { $o = $this->owner ? $this->owner->__toString() : 'none'; return parent::exception($message, $type, $code) ->addMoreInfo('owner', $o) ->addMoreInfo('template', $this->template_source) ; }
Returns relevant exception class. Use this method with "throw". @param string $message Static text of exception. @param string $type Exception class or class postfix @param string $code Optional error code @return Exception_Template
entailment
public function getTagRef($tag, &$template) { if ($this->isTopTag($tag)) { $template = &$this->template; return $this; } @list($tag, $ref) = explode('#', $tag); if (!$ref) { $ref = 1; } if (!isset($this->tags[$tag])) { throw $this->exception('Tag not found in Template') ->addMoreInfo('tag', $tag) ->addMoreInfo('tags', implode(', ', array_keys($this->tags))) ; } $template = reset($this->tags[$tag]); return $this; }
This is a helper method which populates an array pointing to the place in the template referenced by a said tag. Because there might be multiple tags and getTagRef is returning only one template, it will return the first occurence: {greeting}hello{/}, {greeting}world{/} calling getTagRef('greeting',$template) will point second argument towards &array('hello');
entailment
public function getTagRefList($tag, &$template) { if (is_array($tag)) { // TODO: test $res = array(); foreach ($tag as $t) { $template = array(); $this->getTagRefList($t, $te); foreach ($template as &$tpl) { $res[] = &$tpl; } return true; } } if ($this->isTopTag($tag)) { $template = &$this->template; return false; } @list($tag, $ref) = explode('#', $tag); if (!$ref) { if (!isset($this->tags[$tag])) { throw $this->exception('Tag not found in Template') ->setTag($tag); } $template = $this->tags[$tag]; return true; } if (!isset($this->tags[$tag][$ref - 1])) { throw $this->exception('Tag not found in Template') ->setTag($tag); } $template = array(&$this->tags[$tag][$ref - 1]); return true; }
For methods which execute action on several tags, this method will return array of templates. You can then iterate through the array and update all the template values. {greeting}hello{/}, {greeting}world{/} calling getTagRefList('greeting',$template) will point second argument towards array(&array('hello'),&array('world')); If $tag is specified as array, then $templates will contain all occurences of all tags from the array.
entailment
public function hasTag($tag) { if (is_array($tag)) { return true; } @list($tag, $ref) = explode('#', $tag); return isset($this->tags[$tag]) || $this->isTopTag($tag); }
Checks if template has defined a specified tag.
entailment
public function set($tag, $value = null, $encode = true) { if (!$tag) { return $this; } if (is_array($tag)) { if (is_null($value)) { foreach ($tag as $s => $v) { $this->trySet($s, $v, $encode); } return $this; } if (is_array($value)) { throw $this->exception('No longer supported', 'Exception_Obsolete'); } // This can now be used - multiple tags will be set to the value } if (is_array($value)) { return $this; } if ($encode) { $value = htmlspecialchars($value, ENT_NOQUOTES, 'UTF-8'); } $this->getTagRefList($tag, $template); foreach ($template as $key => &$ref) { $ref = array($value); } return $this; }
This function will replace region refered by $tag to a new content. If tag is found inside template several times, all occurences are replaced. ALTERNATIVE USE(2) of this function is to pass associative array as a single argument. This will assign multiple tags with one call. Sample use is: set($_GET); would read and set multiple region values from $_GET array.
entailment
public function del($tag) { if ($this->isTopTag($tag)) { $this->loadTemplateFromString(''); return $this; } $this->getTagRefList($tag, $template); foreach ($template as &$ref) { $ref = array(); // TODO recursively go through template, and add tags // to blacklist, which would then be checked by hasTag() } return $this; }
Empty contents of specified region. If region contains sub-hierarchy, it will be also removed. TODO: This does not dispose of the tags which were previously inside the region. This causes some severe pitfalls for the users and ideally must be checked and proper errors must be generated.
entailment
public function append($tag, $value, $encode = true) { if ($value instanceof URL) { $value = $value->__toString(); } if ($encode) { $value = htmlspecialchars($value, ENT_NOQUOTES, 'UTF-8'); } $this->getTagRefList($tag, $template); foreach ($template as $key => &$ref) { $ref[] = $value; } return $this; }
Add more content inside a tag.
entailment
public function findTemplate($template_name) { /* * Find template location inside search directory path */ if (!$this->app) { throw new Exception_InitError('You should use add() to add objects!'); } $f = $this->app->locatePath( $this->template_type ?: $this->settings['template_type'], $template_name.$this->settings['extension'] ); return $this->origin_filename = $f; }
template loading and parsing
entailment
public function _selector($selector = null) { if ($selector === false) { $this->library = null; } elseif ($selector instanceof self) { $this->library = '$('.$selector.')'; } else { $this->library = '$('.json_encode($selector).')'; } return $this; }
Chain binds to parent object by default. Use this to use other selector $('selector') @param mixed $selector @return $this
entailment
public function _prepend($code) { if (is_array($code)) { $code = implode(';', $code); } $this->prepend = $code.';'.$this->prepend; return $this; }
Execute more JavaScript code before chain. Avoid using. @param array|string $code @return $this
entailment
public function execute() { if (isset($_POST['ajax_submit']) || $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') { //if($this->app->jquery)$this->app->jquery->getJS($this->owner); if (headers_sent($file, $line)) { echo "<br/>Direct output (echo or print) detected on $file:$line. <a target='_blank' " ."href='http://agiletoolkit.org/error/direct_output'>Use \$this->add('Text') instead</a>.<br/>"; } $x = $this->app->template->get('document_ready'); if (is_array($x)) { $x = implode('', $x); } echo $this->_render(); $this->app->hook('post-js-execute'); exit; } else { throw $this ->exception('js()->..->execute() must be used in response to form submission or AJAX operation only'); } }
Send chain in response to form submit, button click or ajaxec() function for AJAX control output.
entailment
public function _safe_js_string($str) { $l = strlen($str); $ret = ''; for ($i = 0; $i < $l; ++$i) { switch ($str[$i]) { case "\r": $ret .= '\\r'; break; case "\n": $ret .= '\\n'; break; case '"': case "'": case '<': case '>': case '&': case '\\': $ret .= '\x'.dechex(ord($str[$i])); break; default: $ret .= $str[$i]; break; } } return $ret; }
[private] used by custom json_encoding @param string $str @return string
entailment
protected function _flattern_objects($arg, $return_comma_list = false) { /* * This function is very similar to json_encode, however it will traverse array * before encoding in search of objects based on AbstractObject. Those would * be replaced with their json representation if function exists, otherwise * with string representation */ if (is_object($arg)) { if ($arg instanceof self) { $r = $arg->_render(); if (substr($r, -1) == ';') { $r = substr($r, 0, -1); } return $r; } elseif ($arg instanceof AbstractView) { return "'#".$arg->getJSID()."'"; } else { return "'".$this->_safe_js_string((string) $arg)."'"; // indirectly call toString(); } } elseif (is_array($arg)) { $a2 = array(); // is array associative? (hash) $assoc = $arg != array_values($arg); foreach ($arg as $key => $value) { $value = $this->_flattern_objects($value); $key = $this->_flattern_objects($key); if (!$assoc || $return_comma_list) { $a2[] = $value; } else { $a2[] = $key.':'.$value; } } if ($return_comma_list) { $s = implode(',', $a2); } elseif ($assoc) { $s = '{'.implode(',', $a2).'}'; } else { $s = '['.implode(',', $a2).']'; } } elseif (is_string($arg)) { $s = "'".$this->_safe_js_string($arg)."'"; } elseif (is_bool($arg)) { $s = json_encode($arg); } elseif (is_numeric($arg)) { $s = json_encode($arg); } elseif (is_null($arg)) { $s = json_encode($arg); } else { throw $this->exception('Unable to encode value for jQuery Chain - unknown type') ->addMoreInfo('arg', var_export($arg, true)); } return $s; }
[private] custom json_encoding. called on function arguments. @param mixed $arg @param bool $return_comma_list @return string
entailment
public function redirect($page = null, $arg = array()) { $url = $this->app->url($page, $arg); return $this->univ()->_fn('redirect', array($url)); }
Calls real redirect (from univ), but accepts page name. Use url() for 1st argument manually anyway. @param string $page Page name @param array $arg Arguments @return $this
entailment
public function reload($arg = array(), $fn = null, $url = null, $interval = null) { if ($fn && $fn instanceof self) { $fn->_enclose(); } $obj = $this->owner; if ($url === null) { $url = $this->app->url(null, array('cut_object' => $obj->name)); } return $this->univ()->_fn('reload', array($url, $arg, $fn, $interval)); }
Reload object. You can bind this to custom event and trigger it if object is not directly accessible. If interval is given, then object will periodically reload itself. @param array $arg @param jQuery_Chain $fn @param string $url @param int $interval Interval in milisec. how often to reload object @return $this
entailment
public function _enclose($fn = null, $preventDefault = false) { // builds structure $('obj').$fn(function(){ $('obj').XX; }); if ($fn === null) { $fn = true; } $this->enclose = $fn; $this->preventDefault = $preventDefault; return $this; }
Chain will not be called but will return callable function instead. @param jQuery_Chain $fn @param bool $preventDefault @return $this
entailment
public function _render() { $ret = $this->prepend; if ($this->library) { $ret .= $this->library; } else { if ($this->str) { $ret .= "$('#".$this->owner->getJSID()."')"; } } $ret .= $this->str; if ($this->enclose === true) { if ($this->preventDefault) { $ret = 'function(ev,ui){ev.preventDefault();ev.stopPropagation(); '.$ret.'}'; } else { $ret = 'function(ev,ui){'.$ret.'}'; } } elseif ($this->enclose) { $ret = ($this->library ?: "$('#".$this->owner->getJSID()."')"). ".bind('".$this->enclose."',function(ev,ui){ev.preventDefault();ev.stopPropagation(); ".$ret.'})'; } if (@$this->debug) { echo "<font color='blue'>".htmlspecialchars($ret).';</font><br/>'; $this->debug = false; } return $ret; }
Render and return js chain as string @return string
entailment
public function addField($name, $alias = null) { $field = $this->add($this->field_class, $name); /** @type Field_Base $field */ $field = $field->actual($alias); /** @type Field_Base $field */ return $field; }
Creates field definition object containing field meta-information such as caption, type validation rules, default value etc. @param string $name @param string $alias @return Field_Base
entailment
public function addExpression($name, $expression, $field_class = UNDEFINED) { if ($field_class === UNDEFINED) { $field_class = $this->defaultExpressionFieldClass; } $field = $this->add($field_class, $name); /** @type Field_Callback $field */ $field->setExpression($expression); $this->_expressions[$name] = $field; return $field; }
Add expression: the value of those field will calculate when you use get method. @param string $name @param mixed $expression @param string $field_class @return Field_Base
entailment
public function set($name, $value = UNDEFINED) { if (is_array($name)) { foreach ($name as $key => $val) { $this->set($key, $val); } return $this; } elseif ($value === UNDEFINED) { throw $this->exception('You must define the second argument'); } if ($this->strict_fields && !$this->hasElement($name)) { throw $this->exception('No such field', 'Logic') ->addMoreInfo('field', $name); } if (($value !== $this->data[$name]) || (is_null($value) && !array_key_exists($name, $this->data))) { $this->data[$name] = $value; $this->setDirty($name); } if ($name === $this->id_field) { $this->id = $value; } return $this; }
Set value of fields. If only a single argument is specified and it is a hash, will use keys as property names and set values accordingly. @param $name array or string @param $value null or value @return $this
entailment
public function get($name = null) { if ($name === null) { $data = $this->data; foreach ($this->_expressions as $key => $field) { $data[$key] = $field->getValue($this, $this->data); } foreach ($this->elements as $key => $field) { if ($field instanceof Field || $field instanceof Field_Base) { if ($field->defaultValue() !== null && !isset($data[$key])) { $data[$key] = $field->defaultValue(); } } } return $data; } /** @type Field_Base $f */ $f = $this->hasElement($name); if ($this->strict_fields && !$f) { throw $this->exception('No such field', 'Logic') ->addMoreInfo('field', $name); } if ($f instanceof Field_Calculated) { return $f->getValue($this, $this->data); } // See if we have data for the field if (!$this->loaded() && !@array_key_exists($name, $this->data)) { if ($f && $f->has_default_value) { return $f->defaultValue(); } if ($this->strict_fields) { throw $this->exception('Model field was not loaded') ->addMoreInfo('id', $this->id) ->addMoreInfo('field', $name); } return; } return $this->data[$name]; }
Get the value of a model field. If field $name is not specified, then returns associative hash containing all field data. @param string $name @return mixed
entailment
public function getGroupField($group = 'all') { $toExclude = array(); $toAdd = array(); if (strpos($group, ',') !== false) { foreach (explode(',', $group) as $g) { if ($g[0] === '-') { $toExclude[] = substr($g, 1); } else { $toAdd[] = $g; } } } else { $toAdd = array($group); } $fields = array(); foreach ($this->elements as $el) { if (!($el instanceof $this->field_class)) { continue; } $elGroup = $el->group(); if (!in_array($elGroup, $toExclude) && ( in_array('all', $toAdd) || in_array($elGroup, $toAdd) ) ) { $fields[] = $el->short_name; } } return $fields; }
Return all fields that belongs to the specified group. You can use the subtractions group also ("all,-group1,-group2"). @param string $group @return array
entailment
public function setActualFields($group = UNDEFINED) { if (is_array($group)) { $this->actual_fields = $group; return $this; } if ($group === UNDEFINED) { $group = 'all'; } $this->actual_fields = $this->getGroupField($group); return $this; }
Set the actual fields of this model. You can use an array to set the list of fields or a string to use the grouping. @param array|string $group string or array @return $this
entailment
public function getActualFields() { if ($this->actual_fields === false) { $this->actual_fields = $this->getGroupField(); } return $this->actual_fields; }
Get the actual fields. @return array the actual fields
entailment
public function getTitleField() { if ($this->title_field && $this->hasElement($this->title_field)) { return $this->title_field; } return $this->id_field; }
Return the title field. @return string the title field
entailment
public function isDirty($name) { /** @type Field_Base $field */ $field = $this->getElement($name); return $this->dirty[$name] || (!$this->loaded() && $field->has_default_value); }
Return true if the field is set. @param string $name @return bool
entailment
public function setControllerData($controller) { if (is_string($controller)) { $controller = $this->app->normalizeClassName($controller, 'Data'); } elseif (!$controller instanceof Controller_Data) { throw $this->exception('Inappropriate Controller. Must extend Controller_Data'); } $this->controller = $this->setController($controller); return $this->controller; }
Set the controller data of this model. @param string|Controller_Data $controller @return Controller_Data
entailment
public function setControllerSource($table = null) { if (is_null($this->controller)) { throw $this->exception('Call setControllerData before'); } $this->controller->setSource($this, $table); }
Set the source to the controller data. The $table argument depends on the controller data implementation. @param mixed $table
entailment
public function setSource($controller, $table = null) { $this->setControllerData($controller); $this->setControllerSource($table); return $this; }
Associate model with a specified data source. The controller could be either a string (postfix for Controller_Data_..) or a class. One data controller may be used with multiple models. If the $table argument is not specified then :php:attr:`Model::table` will be used to find out name of the table / collection.
entailment
public function supports($feature) { if (!$this->controller) { return false; } $s = 'support'.$feature; return $this->controller->$s; }
Returns if certain feature is supported by model
entailment
public function load($id) { if (!$this->controller) { throw $this->exception('Unable to load model, setSource() must be set'); } if ($this->loaded()) { $this->unload(); } $this->hook('beforeLoad', array('load', array($id))); $this->controller->loadById($this, $id); $this->endLoad(); return $this; }
Like tryLoad method but if the record not found, an exception is thrown. @param $id @return $this
entailment
public function loadAny() { if ($this->loaded()) { $this->unload(); } $this->hook('beforeLoad', array('loadAny', array())); $this->controller->loadByConditions($this); $this->endLoad(); return $this; }
Like tryLoadAny method but if the record not found, an exception is thrown. @return $this
entailment
public function loadBy($field, $cond, $value = UNDEFINED) { if ($field == $this->id_field && $value === UNDEFINED) { return $this->load($cond); } if ($field == $this->id_field && cond === '=') { return $this->load($value); } if ($this->loaded()) { $this->unload(); } $this->hook('beforeLoad', array('loadBy', array($field, $cond, $value))); $conditions = $this->conditions; $this->addCondition($field, $cond, $value); $this->controller->loadByConditions($this); $this->conditions = $conditions; $this->endLoad(); return $this; }
Like tryLoadBy method but if the record not found, an exception is thrown. @param $field @param $cond @param $value @return $this
entailment
public function tryLoadBy($field, $cond = UNDEFINED, $value = UNDEFINED) { try { $this->loadBy($field, $cond, $value); } catch (Exception_NotFound $e) { // ignore not-found exception } return $this; }
Adding temporally condition to the model to retrive the first record The condition specified is removed after the controller data call. @param $field @param $cond @param $value @return $this
entailment
public function unload() { if ($this->_save_later) { $this->_save_later = false; $this->saveAndUnload(); } if ($this->loaded()) { $this->hook('beforeUnload'); } $this->data = $this->dirty = array(); $this->id = null; $this->hook('afterUnload'); return $this; }
Forget loaded data. @return $this
entailment
public function reset() { $ret = $this->unload(); $this->_table = array(); $this->conditions = array(); $this->order = array(); $this->limit = array(); return $ret; }
Same as unload() method. @return $this
entailment
public function save() { $this->hook('beforeSave', array($this->id)); $is_update = $this->loaded(); if ($is_update) { $source = array(); foreach ($this->dirty as $name => $junk) { $source[$name] = $this->get($name); } // No save needed, nothing was changed if (empty($source)) { return $this; } $this->hook('beforeUpdate', array(&$source)); } else { // Collect all data of a new record $source = $this->get(); $this->hook('beforeInsert', array(&$source)); } if ($this->controller) { $this->id = $this->controller->save($this, $this->id, $source); } if ($is_update) { $this->hook('afterUpdate'); } else { $this->hook('afterInsert'); } if ($this->loaded()) { $this->dirty = array(); $this->hook('afterSave', array($this->id)); } return $this; }
Saves record with current controller. Uses $this->id as primary key. If not set, new record is created.
entailment
public function delete($id = null) { if ($this->loaded() && !is_null($id) && ($id !== $this->id)) { throw $this->exception('Unable to determine which record to delete'); } if (!is_null($id) && (!$this->loaded() || ($this->loaded() && $id !== $this->id))) { $this->load($id); } if (!$this->loaded()) { throw $this->exception('Unable to determine which record to delete'); } $id = $this->id; $this->hook('beforeDelete', array($id)); $this->controller->delete($this, $id); $this->hook('afterDelete', array($id)); $this->unload(); return $this; }
Delete a record. If the model is loaded, delete the current id. If not loaded, load model through the $id parameter and delete.
entailment
public function deleteAll() { if ($this->loaded()) { $this->unload(); } $this->hook('beforeDeleteAll'); $this->controller->deleteAll($this); $this->hook('afterDeleteAll'); return $this; }
Deletes all records associated with this model.
entailment
public function addCondition($field, $operator = UNDEFINED, $value = UNDEFINED) { if (!$this->controller) { throw $this->exception('Controller for this model is not set', 'NotImplemented'); } if (!@$this->controller->supportConditions) { throw $this->exception('The controller doesn\'t support conditions', 'NotImplemented') ->addMoreInfo('controller', $this->controller); } if (is_array($field)) { foreach ($field as $value) { $this->addCondition($value[0], $value[1], count($value) === 2 ? UNDEFINED : $value[2]); } return $this; } elseif (($operator === UNDEFINED) && (!is_object($field))) { // controller can handle objects throw $this->exception('You must define the second argument'); } if ($value === UNDEFINED) { $value = $operator; $operator = '='; } $supportOperators = $this->controller->supportOperators; if ($supportOperators !== 'all' && (is_null($supportOperators) || (!isset($supportOperators[$operator])))) { throw $this->exception('Unsupport operator', 'NotImplemented') ->addMoreInfo('operator', $operator); } $this->conditions[] = array($field, $operator, $value); return $this; }
Adds a new condition for this model
entailment
public function count($alias = null) { if ($this->controller && $this->controller->hasMethod('count')) { return $this->controller->count($this, $alias); } throw $this->exception('The controller doesn\'t support count', 'NotImplemented') ->addMoreInfo('controller', $this->controller ? $this->controller->short_name : 'none'); }
Count records of model. @param string $alias Optional alias of count result @return int
entailment
public function hasOne($model, $our_field = UNDEFINED, $field_class = UNDEFINED) { if ($field_class === UNDEFINED) { $field_class = $this->defaultHasOneFieldClass; } if ($our_field === UNDEFINED) { // guess our field $tmp = $this->app->normalizeClassName($model, 'Model'); $tmp = new $tmp(); // avoid recursion $refFieldName = ($tmp->table ?: strtolower(get_class($this))).'_id'; } else { $refFieldName = $our_field; } $displayFieldName = preg_replace('/_id$/', '', $our_field); $field = $this->addField($refFieldName); if (!@$this->controller->supportExpressions) { $expr = $this->addExpression($displayFieldName, $model, $field_class) ->setModel($model) ->setForeignFieldName($refFieldName); $this->_references[$refFieldName] = $model; return $expr; } return $field; }
{{{ Relational methods
entailment
public function ref($ref1) { list($ref, $rest) = explode('/', $ref1, 2); if (!isset($this->_references[$ref])) { /** @type Field_Base $e */ $e = $this->hasElement($ref); if ($e && $e->hasMethod('ref')) { return $e->ref(); } else { throw $this->exception('Reference is not defined') ->addMoreInfo('model', $this) ->addMoreInfo('ref', $ref); } } $class = $this->_references[$ref]; if (is_array($class)) { // hasMany if ($rest) { throw $this->exception('Cannot traverse multiple references'); } $m = $this->_ref( $class[0], $class[1] && $class[1] != UNDEFINED ? $class[1] : $this->table.'_id', $class[2] && $class[2] != UNDEFINED ? $this[$class[2]] : $this->id ); } else { // hasOne $id = $this->get($ref); /** @type Model $m */ $m = $this->_ref( $class, null, $id ); if ($id) { $this->hook('beforeRefLoad', array($m, $id)); $m->load($id); } } if ($rest) { $m = $m->ref($rest); } return $m; }
Traverses reference of relation. @param string $ref1 @return Model
entailment
public function init() { /* * During form initialization it will go through it's own template and * search for lots of small template chunks it will be using. If those * chunk won't be in template, it will fall back to default values. * This way you can re-define how form will look, but only what you need * in particular case. If you don't specify template at all, form will * work with default look. */ parent::init(); $this->getChunks(); // After init method have been executed, it's safe for you to add // controls on the form. BTW, if you want to have default values such as // loaded from the table, then intialize $this->data array to default // values of those fields. $this->app->addHook('pre-exec', array($this, 'loadData')); $this->app->addHook('pre-render-output', array($this, 'lateSubmit')); $this->app->addHook('submitted', array($this, 'submitted')); $this->addHook('afterAdd', array($this, 'afterAdd')); }
}}}
entailment
public function error($field, $text = null) { /** @type Form_Field $form_field */ $form_field = $this->getElement($field); $form_field->displayFieldError($text); }
Adds error message to form field. @param string $field @param string $text
entailment
public function addField($type, $options = null, $caption = null, $attr = null) { $insert_into = $this->layout ?: $this; if (is_object($type) && $type instanceof AbstractView && !($type instanceof Form_Field)) { // using callback on a sub-view $insert_into = $type; list(, $type, $options, $caption, $attr) = func_get_args(); } if ($options === null) { $options = $type; $type = 'Line'; } if (is_array($options)) { $name = isset($options['name']) ? $options['name'] : null; } else { $name = $options; // backward compatibility } $name = preg_replace('|[^a-z0-9-_]|i', '_', $name); if ($caption === null) { $caption = ucwords(str_replace('_', ' ', $name)); } /* normalzie name and put name back in options array */ $name = $this->app->normalizeName($name); if (is_array($options)) { $options['name'] = $name; } else { $options = array('name' => $name); } $map = array( 'dropdown' => 'DropDown', 'checkboxlist' => 'CheckboxList', 'hidden' => 'Hidden', 'text' => 'Text', 'line' => 'Line', 'upload' => 'Upload', 'radio' => 'Radio', 'checkbox' => 'Checkbox', 'password' => 'Password', 'timepicker' => 'TimePicker', ); $key = strtolower($type); $class = array_key_exists($key, $map) ? $map[$key] : $type; $class = $this->app->normalizeClassName($class, 'Form_Field'); if ($insert_into === $this) { $template = $this->template->cloneRegion('form_line'); $field = $this->add($class, $options, null, $template); } else { if ($insert_into->template->hasTag($name)) { $this->template->cloneRegion('field_input'); $options['show_input_only'] = true; $field = $insert_into->add($class, $options, $name); } else { $template = $this->template->cloneRegion('form_line'); $field = $insert_into->add($class, $options, null, $template); } // Keep Reference, for $form->getElement(). $this->elements[$options['name']] = $field; } /** @type Form_Field $field */ $field->setCaption($caption); $field->setForm($this); $field->template->trySet('field_type', strtolower($type)); if ($attr) { if ($this->app->compat_42) { $field->setAttr($attr); } else { throw $this->exception('4th argument to addField is obsolete'); } } return $field; }
Adds field in form. @param AbstractView|array|string $type @param AbstractView|array|string $options @param string $caption @param string $attr Deprecated argument @return Form_Field
entailment
public function importFields($model, $fields = null) { /** @type Controller_MVCForm $c */ $c = $this->add($this->default_controller); $c->importFields($model, $fields); }
Imports model fields in form by using form controller. @param Model $model @param array|string|bool $fields
entailment
public function set($field_or_array, $value = UNDEFINED) { // We use UNDEFINED, because 2nd argument of "null" is meaningfull if (is_array($field_or_array)) { foreach ($field_or_array as $key => $val) { if (isset($this->elements[$key]) && ($this->elements[$key] instanceof Form_Field)) { $this->set($key, $val); } } return $this; } if (!isset($this->elements[$field_or_array])) { foreach ($this->elements as $key => $val) { echo "$key<br />"; } throw new BaseException("Trying to set value for non-existant field $field_or_array"); } if ($this->elements[$field_or_array] instanceof Form_Field) { $this->elements[$field_or_array]->set($value); } else { //throw new BaseException("Form fields must inherit from Form_Field ($field_or_array)"); null; } return $this; }
/* temporarily disabled. TODO: will be implemented with abstract datatype function setSource($table,$db_fields=null){ if(is_null($db_fields)){ $db_fields=array(); foreach($this->elements as $key=>$el){ if(!($el instanceof Form_Field))continue; if($el->no_save)continue; $db_fields[]=$key; } } $this->dq = $this->app->db->dsql() ->table($table) ->field('*',$table) ->limit(1); return $this; }
entailment
public function setFieldError($field, $name) { if (!$this->app->compat_42) { throw $this->exception('4.3', '_Obsolete'); } $this->errors[$field] = (isset($this->errors[$field]) ? $this->errors[$field] : '').$name; }
/* external error management
entailment
public function init() { parent::init(); $this->cache = &$this->app->smlite_cache; $this->settings = $this->getDefaultSettings(); $this->settings['extension'] = $this->app->getConfig('smlite/extension', '.html'); }
Template creation, interface functions
entailment
public function get($tag) { if ($this->isTopTag($tag)) { return $this->template; } $v = $this->tags[$tag][0]; if (is_array($v) && count($v) == 1) { $v = array_shift($v); } return $v; }
Finds tag and returns contents. THIS FUNTION IS DANGEROUS! - if you want a rendered region, use renderRegion() - if you want a sub-template use cloneRegion() - if you want to copy part of template to other SMlite object, do not forget to call rebuildTags() if you plan to refer them. Not calling rebuildTags() will render template properly anyway. If tag is defined multiple times, first region is returned.
entailment
public function append($tag, $value, $encode = true) { if ($value instanceof URL) { $value = $value->__toString(); } // Temporary here until we finish testing if ($encode && $value != $this->app->encodeHtmlChars($value, ENT_NOQUOTES) && $this->app->getConfig('html_injection_debug', false) ) { throw $this->exception('Attempted to supply html string through append()') ->addMoreInfo('val', var_export($value, true)) ->addMoreInfo('enc', var_export($this->app->encodeHtmlChars($value, ENT_NOQUOTES), true)) //->addAction('ignore','Ignore tag'.$tag) ; } if ($encode) { $value = $this->app->encodeHtmlChars($value, ENT_NOQUOTES); } if ($this->isTopTag($tag)) { $this->template[] = $value; return $this; } if (!isset($this->tags[$tag]) || !is_array($this->tags[$tag])) { throw $this->exception("Cannot append to tag $tag") ->addMoreInfo('by', $this->owner); } foreach ($this->tags[$tag] as $key => $_) { if (!is_array($this->tags[$tag][$key])) { //throw new BaseException("Problem appending '". // $this->app->encodeHtmlChars($value)."' to '$tag': key=$key"); $this->tags[$tag][$key] = array($this->tags[$tag][$key]); } $this->tags[$tag][$key][] = $value; } return $this; }
This appends static content to region refered by a tag. This function is useful when you are adding more rows to a list or table. If tag is used for several regions inside template, they all will be appended with new data.
entailment
public function setMessage($tag, $args = array()) { if (!is_array($args)) { $args = array($args); } $fmt = $this->app->_($this->get($tag)); // Try to analyze format and see which formatter to use if (class_exists('MessageFormatter', false) && strpos($fmt, '{') !== null) { $fmt = new MessageFormatter($this->app->locale, $fmt); $str = $fmt->format($args); } elseif (strpos($fmt, '%') !== null) { // Else, perhaps it's a sprintf? array_unshift($args, $fmt); $str = call_user_func_array('sprintf', $args); } else { throw $this->exception('Unclear how to format this') ->addMoreInfo('fmt', $fmt) ; } return $this->set($tag, $str); }
Provided that the HTML tag contains ICU-compatible message format string, it will be localized then integrated with passed arguments.
entailment