public function get($formFile, One_Model $model, array $options = array()) { $cx = new One_Context(); $formName = 'oneForm'; $action = ''; $task = 'edit'; $scheme = $model->getScheme(); if (isset($options['action'])) { $action = $options['action']; } if (isset($options['formName'])) { $formName = $options['formName']; } if (is_null($model->task) || trim($model->task) == '') { if (!is_null($cx->get('task'))) { $task = $cx->get('task'); } if (isset($options['task'])) { $task = $options['task']; } } else { $task = $model->task; } $form = One_Form_Factory::createForm($scheme, $formFile, NULL, $formName, $action); return $form; }
public function countRelated(One_Relation_Adapter $link, One_Model $model, array $options = array()) { $linkName = $link->getName(); // identify the target scheme $source = One_Repository::getScheme($model->getSchemeName()); $target = One_Repository::getScheme($link->getTarget()); $backlinks = $target->getLinks(); $backlink = $backlinks[$link->getLinkId()]; if (!$backlink) { throw new One_Exception('The role "' . $roleName . '" does not exist for this model'); } $at = $source->getIdentityAttribute()->getName(); $column = $this->remoteFK($link, $source, $backlink); // bind the data using the data $localValue = $model->{$at}; // create query and execute $q = One_Repository::selectQuery($link->getTarget()); $q->setOptions($options); if (isset($link->meta['hybrid'])) { $var = $link->meta['hybrid'] . '_scheme'; $q->where($var, 'eq', $source->getName()); } $q->where($column, 'eq', $localValue); return $q->getCount(); }
/** * Add a model to the map * * @param One_Model $model */ public static function add(One_Model $model) { $scheme = $model->getSchemeName(); $identity_name = $model->getIdentityName(); $identity = $model->{$identity_name}; if (!$identity) { throw new One_Exception("The model has no identity yet and cannot be stored in the identity map."); } $key = "model.{$scheme}.{$identity}"; if (!self::$registry) { self::$registry = new One_Registry(); } self::$registry->set($key, $model); }
public function countRelated(One_Relation_Adapter $link, One_Model $model, array $options = array()) { $nRelated = 0; $linkName = $link->getName(); // identify the target scheme $source = One_Repository::getScheme($model->getSchemeName()); $target = One_Repository::getScheme($link->getTarget()); $backlinks = $target->getLinks(); $backlink = $backlinks[$link->getLinkId()]; if (!$backlink) { throw new One_Exception("There is no link with id " . $link->getLinkId() . " in scheme " . $link->getTarget()); } $sourceId = $source->getIdentityAttribute()->getName(); $localValue = $model[$sourceId]; $targetId = $target->getIdentityAttribute()->getName(); // TR20100615 if all stores are equal, do normal join, if not, fetch data in several steps // @TODO This should actually be handled in One_Query if ($source->getConnection()->getName() == $link->meta['connection'] && $link->meta['connection'] == $target->getConnection()->getName()) { $lQ = One_Repository::selectQuery($source); $lQ->setSelect(array($linkName . ':*')); $lQ->where($sourceId, 'eq', $localValue); if (array_key_exists('query', $options) && is_array($options['query']) && count($options['query']) > 0) { foreach ($options['query'] as $qKey => $qOption) { if (count($qOption) == 3) { $options['query'][$qKey][0] = $linkName . ':' . $options['query'][$qKey][0]; } } } $lQ->setOptions($options); $nRelated = $lQ->getCount(); } else { $fkLocal = $link->meta['fk:local']; $fkRemote = $link->meta['fk:remote']; $omtms = One_Repository::getScheme('onemanytomany'); $omtms->setConnection(One_Repository::getConnection($link->meta['connection'])); $omtms->setResources($link->meta); $localAtt = new One_Scheme_Attribute($fkLocal, $source->getIdentityAttribute()->getType()->getName()); $remoteAtt = new One_Scheme_Attribute($fkRemote, $target->getIdentityAttribute()->getType()->getName()); $omtms->addAttribute($localAtt); $omtms->addAttribute($remoteAtt); $joinQ = One_Repository::selectQuery($omtms); $joinQ->setSelect(array($fkRemote)); $joinQ->where($fkLocal, 'eq', $localValue); $rawRelatedIDs = $joinQ->execute(false); $related = array(); if (count($rawRelatedIDs) > 0) { $relatedIDs = array(); foreach ($rawRelatedIDs as $row) { $relatedIDs[] = $row->{$fkRemote}; } $lQ = One_Repository::selectQuery($target); $lQ->where($targetId, 'in', $relatedIDs); $lQ->setOptions($options); $nRelated = $lQ->getCount(); } } return $nRelated; }
/** * Bind the model to the widget * * @param One_Model $model */ public function bindModel($model) { $value = $this->requestValue(); // bad name if (is_null($value)) { $value = array(); } // if == NULL, set to 0, because NULL won't be picked up by $model->__modified $attributeName = $this->_name; // When the attributeName starts with 'r__', we're not saving an attribute but a relation if (preg_match('/^r__(.*)_(((?!._).)*)$/iU', $attributeName, $tmp)) { $relName = $tmp[1]; $relRole = $tmp[2]; $relValue = $value; $model->setRelated($relRole, $relValue); } else { $model->{$attributeName} = $value; } }
/** * Render the output of the widget and add it to the DOM * * @param One_Model $model * @param One_Dom $d */ protected function _render($model, One_Dom $dom) { $src = $this->getCfg('src'); if (trim($src) == '') { throw new One_Exception("A field of type 'nscript' should have a 'src'-attribute defining the nanoScript file to parse."); } One_Script_Factory::saveSearchPath(); One_Script_Factory::clearSearchPath(); $useLang = $this->getCfg('language'); if ('' == trim($useLang)) { $useLang = strtolower(One_Config::get('app.language')); } die('deprecated stuff found in ' . __FILE__ . ':' . __LINE); $cps = One_Config::getInstance()->getCustomPaths(); foreach ($cps as $cp) { One_Script_Factory::addSearchPath($cp . '/views/' . One_Config::get('app.name') . '/' . $model->getScheme()->getName() . '/language/' . $useLang . '/'); } foreach ($cps as $cp) { One_Script_Factory::addSearchPath($cp . '/views/' . One_Config::get('app.name') . '/' . $model->getScheme()->getName() . '/'); } $ns = new One_Script(); $ns->load($src); if (!$ns->isError()) { if ($this->getID()) { $ns->set('id', $this->getID()); } if ($this->getName()) { $ns->set('name', $this->getName()); } if ($this->getLabel()) { $ns->set('label', $this->getLabel()); } if ($this->getValue($model)) { $ns->set('value', $this->getValue($model)); } $ns->set('model', $model); $dom->add($ns->execute()); } else { throw new One_Exception($ns->error); } $dom->add($this->value); One_Script_Factory::restoreSearchPath(); }
public function countRelated(One_Relation_Adapter $link, One_Model $model, array $options = array()) { $linkName = $link->getName(); // identify the target scheme $source = One_Repository::getScheme($model->getSchemeName()); // PD 22OCT08 if ($link->getTarget() == '*') { $col = $link->getName() . '_scheme'; $target = One_Repository::getScheme($model->{$col}); } else { $target = One_Repository::getScheme($link->getTarget()); } // determine the target's identity column $column = $this->localFK($link, $target); // bind the data using the data $localValue = $model[$column]; // create query and execute return One_Repository::selectOne($target->getName(), $localValue) ? 1 : 0; }
/** * Convert all the excessive data into a json string * * @param One_Scheme $scheme * @param One_Model $model */ private function flexToJson(One_Scheme $scheme, One_Model $model) { $ignoreAttributes = array_merge(self::$_ignoreAttributes, $scheme->getForeignKeys()); // ignore all local foreign key attributes as well $bOptions = $scheme->get('behaviorOptions.' . strtolower($this->getName())); $flexfield = $bOptions['flexfield']; unset($model->{$flexfield}); // Flexfields should not be set manually // // only auto-set the flexfield, if it's not in the modified fields // // if it is set in the modified fields, then the flex field was intentionally set manually // if(!array_key_exists($flexfield, $model->getModified())) // { $data = $model->toArray(); $attributes = $scheme->get('attributes'); foreach ($attributes as $attr) { unset($data[$attr->getName()]); } foreach ($ignoreAttributes as $ignore) { unset($data[$ignore]); } $model->{$flexfield} = json_encode($data); // } }
/** * Deletes children of a certain model on deletion of the parent model * * @param One_Scheme $scheme * @param One_Model $model */ public function beforeDeleteModel(One_Scheme $scheme, One_Model $model) { $options = $scheme->get('behaviorOptions.deletechildren'); $dependent = explode(';', $options['dependent']); $cascade = explode(';', $options['cascade']); $dependentLeft = array(); if (count($dependent) > 0) { foreach ($dependent as $depends) { if (trim($depends) != '') { $related = $model->getRelated(trim($depends)); if (count($related) > 0) { $dependentLeft[] = trim($depends); break; } } } } if (count($dependentLeft) > 0) { throw new One_Exception('You can not delete this item untill all items of "' . implode('", "', $dependentLeft) . '" have been deleted.'); return false; } else { $tbds = array_merge($dependent, $cascade); if (count($tbds) > 0) { foreach ($tbds as $tbd) { if (trim($tbd) != '') { $related = $model->getRelated($tbd); if (count($related) > 0) { foreach ($related as $relation) { $relation->delete(); } } } } } } return true; }
/** * When the model is loaded, add a slug-field to the model that is composed of the specified fields * * @param One_Scheme $scheme * @param One_Model $model */ public function afterLoadModel(One_Scheme $scheme, One_Model $model) { if (null !== $scheme->getAttribute('slug')) { // don't create the slug if the attribute "slug" actually exists return; } $options = $scheme->get('behaviorOptions.slug'); $createFrom = $options['createFrom']; $parts = preg_split('/\\+/', $createFrom); $mangled = array(); foreach ($parts as $part) { if (preg_match('/^([a-z0-9\\_\\-]+):([a-z0-9\\_\\-]+)$/', $part, $matches) > 0) { $scheme = $model->getScheme(); $link = $scheme->getLink($matches[1]); if (!is_null($link)) { if ($link->getAdapterType() == 'manytoone') { $related = $model->getRelated($matches[1]); if (!is_null($related)) { $targetPart = $matches[2]; $mangle = !is_null($related->{$targetPart}) ? trim($this->mangle($related->{$targetPart})) : NULL; if (!is_null($mangle)) { $mangled[] = $mangle; } } } } } else { $mangle = !is_null($model->{$part}) ? trim($this->mangle($model->{$part})) : NULL; if (!is_null($mangle)) { $mangled[] = $mangle; } } } if (count($mangled) > 0) { $model->slug = implode('_', $mangled); } }
/** * delete a single instance * * @param One_Model $model */ public function delete(One_Model $model) { $scheme = One_Repository::getScheme($model->getSchemeName()); $db = $this->db($scheme); // determine table to insert into $table = $this->getTable($scheme); $sql = 'DELETE FROM ' . $table; $idAttr = $scheme->getIdentityAttribute(); $id = $idAttr->getName(); $value = $model->{$id}; $value = $idAttr->toString(mysql_real_escape_string($value, $db)); $sql .= ' WHERE `' . $id . '` = ' . $value; // execute query if (!mysql_query($sql, $db)) { throw new One_Exception(mysql_error() . $sql); } }
public function getAlias(One_Model $model) { $scheme = $model->getScheme(); $aliasOpts = $scheme->get('behaviorOptions.linkalias'); if (null !== $behaviorOpts && isset($behaviorOpts['attribute'])) { $aliasField = $behaviorOpts['attribute']; $alias = $model->{$aliasField}; } elseif (isset($model->slug)) { $alias = $model->slug; } else { $idAttr = $model->getIdentityName(); $alias = $model->{$idAttr}; } return $alias; }
/** * Get the value * * @param One_Model $model * @return Mixed */ public function getValue($model) { if (!$model) { return null; } // pick up vars entered entered from an invalidly filled in form $session = One_Repository::getSession(); $posted = $session->get('posted', 'OneFormErrors'); if (!in_array($this->getCfg('one'), array('one', 'yes', 'true', '1')) && isset($posted['oneForm'][$this->getName()])) { return $posted['oneForm'][$this->getName()]; } else { if (isset($posted[$this->getName()])) { return $posted[$this->getName()]; } else { $role = $this->getCfg('role'); if (!is_null($role) && $model instanceof One_Model) { $parts = explode(':', $role); $related = $model->getRelated($parts[1]); $relation = One_Repository::getRelation($parts[0]); $role = $relation->getRole($parts[1]); $relScheme = One_Repository::getScheme($role->schemeName); if ($related instanceof One_Model) { return $related[$relScheme->getIdentityAttribute()->getName()]; } elseif (is_array($related)) { // $related is an array of One_Models $returnValues = array(); foreach ($related as $r) { $returnValues[] = $r[$relScheme->getIdentityAttribute()->getName()]; } return $returnValues; } } else { //PD16FEB10 : add option to pick this up from request if ($this->getCfg('from') != "") { list($source, $key) = preg_split("/:/", $this->getCfg('from')); switch ($source) { case 'request': $from = $_REQUEST; if (!in_array($this->getCfg('one'), array('one', 'yes', 'true', '1'))) { $from = $_REQUEST['oneForm']; } if (isset($from[$key])) { return $from[$key]; } break; } } if ($this->getCfg('novalue') != "novalue") { return $model[$this->getOriginalName()]; } } } } }
/** * delete a single instance * * @param One_Model $model * @return void */ public function delete(One_Model $model) { $scheme = One_Repository::getScheme($model->getSchemeName()); $db = $this->db($scheme); // determine table to insert into $table = $this->getTable($scheme); $sql = 'DELETE FROM ' . $table . ' '; $idAttr = $scheme->getIdentityAttribute(); // $id = $idAttr->getName(); $id = $idAttr->getColumn(); $value = $model->{$id}; $value = $idAttr->toString($value); $where = 'WHERE `' . $id . '` = ' . $value; $db->setQuery($sql . $where); $db->query(); return null; }
/** * Render the output of the widget and add it to the DOM * * @param One_Model $model * @param One_Dom $d */ protected function _render($model, One_Dom $d) { One_Vendor::requireVendor('jquery/one_loader'); One_Vendor::getInstance()->loadScript('jquery/js/jquery.tagify.js', 'head', 10); if (is_null($this->getCfg('role')) || is_null($this->getCfg('targetAttribute'))) { throw new One_Exception('The Multi-tag widget is only allowed for Many-to-many relations'); } $parts = explode(':', $this->getCfg('role'), 2); $targetAttr = $this->getCfg('targetAttribute'); $link = $model->getScheme()->getLink($parts[1]); if (is_null($link) || !$link->getAdapterType() instanceof One_Relation_Adapter_Manytomany) { throw new One_Exception('The Multi-tag widget is only allowed for Many-to-many relations'); } $tScheme = One_Repository::getScheme($model->getScheme()->getLink($parts[1])->getTarget()); $tIdAttr = $tScheme->getIdentityAttribute()->getName(); // set initial values $value = array(); $values = is_null($this->getValue($model)) ? $this->getDefault() : $this->getValue($model); foreach ($values as $tId) { $tModel = One_Repository::selectOne($tScheme->getName(), $tId); if (null !== $tModel) { $value[$tModel->{$tIdAttr}] = $tModel->{$targetAttr}; } } $data = array('id' => $this->getID(), 'name' => $this->getFormName(), 'events' => $this->getEventsAsString(), 'params' => $this->getParametersAsString(), 'required' => $this->isRequired() ? ' *' : '', 'options' => $this->getOptions(), 'info' => $this->getCfg('info'), 'error' => $this->getCfg('error'), 'class' => $this->getCfg('class'), 'label' => $this->getLabel(), 'lblLast' => $this->getCfg('lblLast')); $dom = $this->parse($model, $data); // $dom->add('<script type="text/javascript" href="'.One_Vendor::getInstance()->getSitePath().'/jquery/js/jquery.tagify.js" />'."\n", '_head'); // $dom->add('<link rel="stylesheet" type="text/css" href="'.One_Vendor::getInstance()->getSitePath().'/jquery/css/tagify-style.css" />'."\n", '_head'); //One_Vendor::getInstance()->loadScript('jquery/js/jquery.tagify.js', 'head', 20); One_Vendor::getInstance()->loadStyle('jquery/css/tagify-style.css', 'head', 20); // Prepare autocomplete tagfield $script = ' var oneTags' . $this->getID() . ' = jQuery("#' . $this->getID() . '").tagify(); oneTags' . $this->getID() . '.tagify("inputField").autocomplete({ source: function(req, add) { req.field = "' . $targetAttr . '"; req.query = "formtags"; //pass request to server jQuery.getJSON("' . One_Config::getInstance()->getSiterootUrl() . One_Config::getInstance()->getAddressOne() . '&scheme=' . $tScheme->getName() . '&task=json", req, function(data) { //create array for response objects var suggestions = []; //process response jQuery.each(data, function(i, val) { var keyval = { "label": val.' . $targetAttr . ', "value": val.' . $tIdAttr . ' }; suggestions.push(keyval); }); //pass array to callback add(suggestions); }); }, position: { of: oneTags' . $this->getID() . '.tagify("containerDiv") }, select: function(e, ui) { oneTags' . $this->getID() . '.tagify("inputField").val(ui.item.label); oneTags' . $this->getID() . '.tagify("add", ui.item.value, ui.item.label); oneTags' . $this->getID() . '.tagify("inputField").val(""); return false; }, focus: function(e, ui) { oneTags' . $this->getID() . '.tagify("inputField").val(ui.item.label); return false; }, change: function(e, ui) { oneTags' . $this->getID() . '.tagify("inputField").val(""); return false; } }); '; foreach ($value as $tId => $tVal) { $script .= ' oneTags' . $this->getID() . '.tagify("add", "' . $tId . '", "' . $tVal . '");'; } // $dom->add($script, '_onload'); One_Vendor::getInstance()->loadScriptDeclaration($script, 'onload', 20); $d->addDom($dom); }
/** * Render the output of the widget and add it to the DOM * * @param One_Model $model * @param One_Dom $d */ protected function _render($model, One_Dom $d) { $this->setCfg('class', 'OneFieldDropdown ' . $this->getCfg('class')); // fetch all data to do with the relationship $parts = explode(':', $this->getCfg('role')); $related = $model->getRelated($parts[1]); $targetAttr = $this->getCfg('targetAttribute'); $triggerOn = intval($this->getCfg('triggerOn')) > 0 ? intval($this->getCfg('triggerOn')) : 2; $scheme = $model->getScheme(); $idAttr = $scheme->getIdentityAttribute()->getName(); $link = $scheme->getLink($parts[1]); $relatedIDs = ''; $options = array(); if (is_array($related) && count($related) > 0) { $relatedIDArray = array(); $idAttr = One_Repository::getScheme($link->getTarget())->getIdentityAttribute()->getName(); $tparts = explode(':', $targetAttr); foreach ($related as $relate) { if (is_null($idAttr)) { $scheme = $model->getScheme(); $idAttr = $scheme->getIdentityAttribute()->getName(); } $value = $relate->{$idAttr}; $shown = ''; foreach ($tparts as $tpart) { $shown .= $relate->{$tpart} . ' '; } $options[$value] = $shown; $relatedIDArray[] = $relate->{$idAttr}; } $relatedIDs = implode('^,^', $relatedIDArray); } $data = array('id' => $this->getID(), 'name' => $this->getFormName(), 'events' => $this->getEventsAsString(), 'params' => $this->getParametersAsString(), 'required' => $this->isRequired() ? ' *' : '', 'value' => is_null($this->getValue($model)) ? $this->getDefault() : $this->getValue($model), 'options' => $options, 'onEmpty' => strtolower($this->getCfg('onEmpty')), 'triggerOn' => $triggerOn, 'scheme' => $scheme, 'link' => $link, 'targetAttr' => $targetAttr, 'modelID' => $model->{$idAttr}, 'relatedIDs' => $relatedIDs, 'info' => $this->getCfg('info'), 'error' => $this->getCfg('error'), 'class' => $this->getCfg('class'), 'label' => $this->getLabel(), 'lblLast' => $this->getCfg('lblLast')); // $dom = new One_Dom(); // dom for head section // // $head = '<script type="text/javascript" src="' . One::getInstance()->getUrl() . 'lib/libraries/js/featherajax.js"></script>'; // $dom->add( $head, '_head' ); $head = ' function setRelatedOptions( selfscheme, scheme, selfId, id, targetAttribute, phrase ) { var self = ""; if( selfscheme == scheme ) self = "&selfId=" + selfId; var aj = new AjaxObject101(); aj.sndReq( "post", "' . One_Config::getInstance()->getUrl() . '/lib/form/ajax/relational.php", "searchscheme=" + scheme + "&dd=f" + id + "&target=" + targetAttribute + "&phrase=" + phrase + self ); } function addChosenOptions( id ) { var dropdown = document.getElementById( "f" + id ); var to = document.getElementById( "t" + id ); for( var i = 0; i < dropdown.length; i++ ) { if( dropdown.options[i].selected == true ) { var option = document.createElement("option"); option.value = dropdown.options[i].value; option.innerHTML = dropdown.options[i].text; var found = false for( var j = 0; j < to.length; j++ ) { if( option.value == to.options[j].value ) { found = true; break; } } if( !found ) { var hidden = document.getElementById( id ); to.appendChild( option ); if( hidden.value != "" ) hidden.value = hidden.value + "^,^" + option.value; else hidden.value = option.value; } } } } function removeChosenOptions( id ) { var to = document.getElementById( "t" + id ); var hidden = document.getElementById( id ); for( var i = ( to.length - 1 ); i >= 0; i-- ) { if( to.options[i].selected == true ) { var pattern = \'((\\^,\\^)?\' + to.options[i].value + \'(\\^,\\^)?)\'; var test = new RegExp( pattern, "gi" ); /* @TODO There is probably an easier way to do this */ hidden.value = hidden.value.replace( test, "" ); hidden.value = hidden.value.replace( /\\^,\\^\\^,\\^/gi, "^,^" ); hidden.value = hidden.value.replace( /^\\^,\\^/gi, "" ); hidden.value = hidden.value.replace( /\\^,\\^$/gi, "" ); to.remove( i ); } } }'; // $dom->add( $head, '_head' ); One_Vendor::getInstance()->loadScript('js/featherajax.js', 200); One_Vendor::getInstance()->loadScriptDeclaration($head, 'head', 200); $content = $this->parse($model, $data); // $d->addDom($dom); $d->addDom($content); }