Related
I am currently upgrading Laravel 5.4 to 5.5 and I saw this:
The has Method
The $request->has method will now return true even if the input value is an empty string or null. A new $request->filled method has been added that provides the previous behavior of the has method.
Does this also apply to blade files?
Eg
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
#if(session()->has('success'))
<script type="text/javascript">x</script>
#endif
And also does it affect files too? Eg
if ($request->hasFile('images') == false) {
//No image..
}
no change on any of these from version 5.4 to 5.5
session()->has('success')
$errors->has('email')
$request->hasFile('images')
changed from version 5.4 to 5.5
$request->has('something');
Below source codes are from the official github tags
Here is the Illuminate\Http's (for $request)
http has() method has been changed
has() from 5.4
/**
* Determine if the request contains a non-empty value for an input item.
*
* #param string|array $key
* #return bool
*/
public function has($key)
{
$keys = is_array($key) ? $key : func_get_args();
foreach ($keys as $value) {
if ($this->isEmptyString($value)) {
return false;
}
}
return true;
}
has() from 5.5
/**
* Determine if the request contains a given input item key.
*
* #param string|array $key
* #return bool
*/
public function has($key)
{
$keys = is_array($key) ? $key : func_get_args();
$input = $this->all();
foreach ($keys as $value) {
if (! Arr::has($input, $value)) {
return false;
}
}
return true;
}
hasFile() is same
hasFile() from 5.4
/**
* Determine if the uploaded data contains a file.
*
* #param string $key
* #return bool
*/
public function hasFile($key)
{
if (! is_array($files = $this->file($key))) {
$files = [$files];
}
foreach ($files as $file) {
if ($this->isValidFile($file)) {
return true;
}
}
return false;
}
hasFile() from 5.5
/**
* Determine if the uploaded data contains a file.
*
* #param string $key
* #return bool
*/
public function hasFile($key)
{
if (! is_array($files = $this->file($key))) {
$files = [$files];
}
foreach ($files as $file) {
if ($this->isValidFile($file)) {
return true;
}
}
return false;
}
Here is the Illumnate\Session's (for session())
session has() method is same
from 5.4
/**
* Checks if a key is present and not null.
*
* #param string|array $key
* #return bool
*/
public function has($key)
{
return ! collect(is_array($key) ? $key : func_get_args())->contains(function ($key) {
return is_null($this->get($key));
});
}
session from 5.5
/**
* Checks if a key is present and not null.
*
* #param string|array $key
* #return bool
*/
public function has($key)
{
return ! collect(is_array($key) ? $key : func_get_args())->contains(function ($key) {
return is_null($this->get($key));
});
}
Here is Illuminate\Support's MessageBag.php (for $errors)
has() from 5.4
/**
* Determine if messages exist for all of the given keys.
*
* #param array|string $key
* #return bool
*/
public function has($key)
{
if (is_null($key)) {
return $this->any();
}
$keys = is_array($key) ? $key : func_get_args();
foreach ($keys as $key) {
if ($this->first($key) === '') {
return false;
}
}
return true;
}
has() from 5.5
/**
* Determine if messages exist for all of the given keys.
*
* #param array|string $key
* #return bool
*/
public function has($key)
{
if (is_null($key)) {
return $this->any();
}
$keys = is_array($key) ? $key : func_get_args();
foreach ($keys as $key) {
if ($this->first($key) === '') {
return false;
}
}
return true;
}
I am getting error in admin panel after adding plugin.
Error :
Fatal error: Call to a member function toOptionArray() on a non-object in /var/lib/openshift/5374ca8999fc775bdc00009d/app-root/runtime/repo/php/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php on line 463
Here is the code :
public function toOptionArray() {
return array(
array('value'=>'0', 'label'=>'No Credit'),
array('value'=>'1', 'label'=>'Credit Only Invited Customer'),
array('value'=>'2', 'label'=>'Credit Only Customer who invite'),
array('value'=>'3', 'label'=>'Credit Both Customer')
);
Form.php file :
<?php
class Mage_Adminhtml_Block_System_Config_Form extends Mage_Adminhtml_Block_Widget_Form
{
const SCOPE_DEFAULT = 'default';
const SCOPE_WEBSITES = 'websites';
const SCOPE_STORES = 'stores';
/**
* Config data array
*
* #var array
*/
protected $_configData;
/**
* Adminhtml config data instance
*
* #var Mage_Adminhtml_Model_Config_Data
*/
protected $_configDataObject;
/**
* Enter description here...
*
* #var Varien_Simplexml_Element
*/
protected $_configRoot;
/**
* Enter description here...
*
* #var Mage_Adminhtml_Model_Config
*/
protected $_configFields;
/**
* Enter description here...
*
* #var Mage_Adminhtml_Block_System_Config_Form_Fieldset
*/
protected $_defaultFieldsetRenderer;
/**
* Enter description here...
*
* #var Mage_Adminhtml_Block_System_Config_Form_Field
*/
protected $_defaultFieldRenderer;
/**
* Enter description here...
*
* #var array
*/
protected $_fieldsets = array();
/**
* Translated scope labels
*
* #var array
*/
protected $_scopeLabels = array();
/**
* Enter description here...
*
*/
public function __construct()
{
parent::__construct();
$this->_scopeLabels = array(
self::SCOPE_DEFAULT => Mage::helper('adminhtml')->__('[GLOBAL]'),
self::SCOPE_WEBSITES => Mage::helper('adminhtml')->__('[WEBSITE]'),
self::SCOPE_STORES => Mage::helper('adminhtml')->__('[STORE VIEW]'),
);
}
/**
* Enter description here...
*
* #return Mage_Adminhtml_Block_System_Config_Form
*/
protected function _initObjects()
{
/** #var $_configDataObject Mage_Adminhtml_Model_Config_Data */
$this->_configDataObject = Mage::getSingleton('adminhtml/config_data');
$this->_configRoot = $this->_configDataObject->getConfigRoot();
$this->_configData = $this->_configDataObject->load();
$this->_configFields = Mage::getSingleton('adminhtml/config');
$this->_defaultFieldsetRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_fieldset');
$this->_defaultFieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
return $this;
}
/**
* Enter description here...
*
* #return Mage_Adminhtml_Block_System_Config_Form
*/
public function initForm()
{
$this->_initObjects();
$form = new Varien_Data_Form();
$sections = $this->_configFields->getSection(
$this->getSectionCode(),
$this->getWebsiteCode(),
$this->getStoreCode()
);
if (empty($sections)) {
$sections = array();
}
foreach ($sections as $section) {
/* #var $section Varien_Simplexml_Element */
if (!$this->_canShowField($section)) {
continue;
}
foreach ($section->groups as $groups){
$groups = (array)$groups;
usort($groups, array($this, '_sortForm'));
foreach ($groups as $group){
/* #var $group Varien_Simplexml_Element */
if (!$this->_canShowField($group)) {
continue;
}
$this->_initGroup($form, $group, $section);
}
}
}
$this->setForm($form);
return $this;
}
/**
* Init config group
*
* #param Varien_Data_Form $form
* #param Varien_Simplexml_Element $group
* #param Varien_Simplexml_Element $section
* #param Varien_Data_Form_Element_Fieldset|null $parentElement
*/
protected function _initGroup($form, $group, $section, $parentElement = null)
{
if ($group->frontend_model) {
$fieldsetRenderer = Mage::getBlockSingleton((string)$group->frontend_model);
} else {
$fieldsetRenderer = $this->_defaultFieldsetRenderer;
}
$fieldsetRenderer->setForm($this)
->setConfigData($this->_configData);
if ($this->_configFields->hasChildren($group, $this->getWebsiteCode(), $this->getStoreCode())) {
$helperName = $this->_configFields->getAttributeModule($section, $group);
$fieldsetConfig = array('legend' => Mage::helper($helperName)->__((string)$group->label));
if (!empty($group->comment)) {
$fieldsetConfig['comment'] = Mage::helper($helperName)->__((string)$group->comment);
}
if (!empty($group->expanded)) {
$fieldsetConfig['expanded'] = (bool)$group->expanded;
}
$fieldset = new Varien_Data_Form_Element_Fieldset($fieldsetConfig);
$fieldset->setId($section->getName() . '_' . $group->getName())
->setRenderer($fieldsetRenderer)
->setGroup($group);
if ($parentElement) {
$fieldset->setIsNested(true);
$parentElement->addElement($fieldset);
} else {
$form->addElement($fieldset);
}
$this->_prepareFieldOriginalData($fieldset, $group);
$this->_addElementTypes($fieldset);
$this->_fieldsets[$group->getName()] = $fieldset;
if ($group->clone_fields) {
if ($group->clone_model) {
$cloneModel = Mage::getModel((string)$group->clone_model);
} else {
Mage::throwException($this->__('Config form fieldset clone model required to be able to clone fields'));
}
foreach ($cloneModel->getPrefixes() as $prefix) {
$this->initFields($fieldset, $group, $section, $prefix['field'], $prefix['label']);
}
} else {
$this->initFields($fieldset, $group, $section);
}
}
}
/**
* Return dependency block object
*
* #return Mage_Adminhtml_Block_Widget_Form_Element_Dependence
*/
protected function _getDependence()
{
if (!$this->getChild('element_dependense')){
$this->setChild('element_dependense',
$this->getLayout()->createBlock('adminhtml/widget_form_element_dependence'));
}
return $this->getChild('element_dependense');
}
/**
* Init fieldset fields
*
* #param Varien_Data_Form_Element_Fieldset $fieldset
* #param Varien_Simplexml_Element $group
* #param Varien_Simplexml_Element $section
* #param string $fieldPrefix
* #param string $labelPrefix
* #return Mage_Adminhtml_Block_System_Config_Form
*/
public function initFields($fieldset, $group, $section, $fieldPrefix='', $labelPrefix='')
{
if (!$this->_configDataObject) {
$this->_initObjects();
}
// Extends for config data
$configDataAdditionalGroups = array();
foreach ($group->fields as $elements) {
$elements = (array)$elements;
// sort either by sort_order or by child node values bypassing the sort_order
if ($group->sort_fields && $group->sort_fields->by) {
$fieldset->setSortElementsByAttribute(
(string)$group->sort_fields->by,
$group->sort_fields->direction_desc ? SORT_DESC : SORT_ASC
);
} else {
usort($elements, array($this, '_sortForm'));
}
foreach ($elements as $element) {
if (!$this->_canShowField($element)) {
continue;
}
if ((string)$element->getAttribute('type') == 'group') {
$this->_initGroup($fieldset->getForm(), $element, $section, $fieldset);
continue;
}
/**
* Look for custom defined field path
*/
$path = (string)$element->config_path;
if (empty($path)) {
$path = $section->getName() . '/' . $group->getName() . '/' . $fieldPrefix . $element->getName();
} elseif (strrpos($path, '/') > 0) {
// Extend config data with new section group
$groupPath = substr($path, 0, strrpos($path, '/'));
if (!isset($configDataAdditionalGroups[$groupPath])) {
$this->_configData = $this->_configDataObject->extendConfig(
$groupPath,
false,
$this->_configData
);
$configDataAdditionalGroups[$groupPath] = true;
}
}
$data = $this->_configDataObject->getConfigDataValue($path, $inherit, $this->_configData);
if ($element->frontend_model) {
$fieldRenderer = Mage::getBlockSingleton((string)$element->frontend_model);
} else {
$fieldRenderer = $this->_defaultFieldRenderer;
}
$fieldRenderer->setForm($this);
$fieldRenderer->setConfigData($this->_configData);
$helperName = $this->_configFields->getAttributeModule($section, $group, $element);
$fieldType = (string)$element->frontend_type ? (string)$element->frontend_type : 'text';
$name = 'groups[' . $group->getName() . '][fields][' . $fieldPrefix.$element->getName() . '][value]';
$label = Mage::helper($helperName)->__($labelPrefix) . ' '
. Mage::helper($helperName)->__((string)$element->label);
$hint = (string)$element->hint ? Mage::helper($helperName)->__((string)$element->hint) : '';
if ($element->backend_model) {
$model = Mage::getModel((string)$element->backend_model);
if (!$model instanceof Mage_Core_Model_Config_Data) {
Mage::throwException('Invalid config field backend model: '.(string)$element->backend_model);
}
$model->setPath($path)
->setValue($data)
->setWebsite($this->getWebsiteCode())
->setStore($this->getStoreCode())
->afterLoad();
$data = $model->getValue();
}
$comment = $this->_prepareFieldComment($element, $helperName, $data);
$tooltip = $this->_prepareFieldTooltip($element, $helperName);
$id = $section->getName() . '_' . $group->getName() . '_' . $fieldPrefix . $element->getName();
if ($element->depends) {
foreach ($element->depends->children() as $dependent) {
/* #var $dependent Mage_Core_Model_Config_Element */
if (isset($dependent->fieldset)) {
$dependentFieldGroupName = (string)$dependent->fieldset;
if (!isset($this->_fieldsets[$dependentFieldGroupName])) {
$dependentFieldGroupName = $group->getName();
}
} else {
$dependentFieldGroupName = $group->getName();
}
$dependentFieldNameValue = $dependent->getName();
$dependentFieldGroup = $dependentFieldGroupName == $group->getName()
? $group
: $this->_fieldsets[$dependentFieldGroupName]->getGroup();
$dependentId = $section->getName()
. '_' . $dependentFieldGroupName
. '_' . $fieldPrefix
. $dependentFieldNameValue;
$shouldBeAddedDependence = true;
$dependentValue = (string)(isset($dependent->value) ? $dependent->value : $dependent);
if (isset($dependent['separator'])) {
$dependentValue = explode((string)$dependent['separator'], $dependentValue);
}
$dependentFieldName = $fieldPrefix . $dependent->getName();
$dependentField = $dependentFieldGroup->fields->$dependentFieldName;
/*
* If dependent field can't be shown in current scope and real dependent config value
* is not equal to preferred one, then hide dependence fields by adding dependence
* based on not shown field (not rendered field)
*/
if (!$this->_canShowField($dependentField)) {
$dependentFullPath = $section->getName()
. '/' . $dependentFieldGroupName
. '/' . $fieldPrefix
. $dependent->getName();
$dependentValueInStore = Mage::getStoreConfig($dependentFullPath, $this->getStoreCode());
if (is_array($dependentValue)) {
$shouldBeAddedDependence = !in_array($dependentValueInStore, $dependentValue);
} else {
$shouldBeAddedDependence = $dependentValue != $dependentValueInStore;
}
}
if ($shouldBeAddedDependence) {
$this->_getDependence()
->addFieldMap($id, $id)
->addFieldMap($dependentId, $dependentId)
->addFieldDependence($id, $dependentId, $dependentValue);
}
}
}
$sharedClass = '';
if ($element->shared && $element->config_path) {
$sharedClass = ' shared shared-' . str_replace('/', '-', $element->config_path);
}
$requiresClass = '';
if ($element->requires) {
$requiresClass = ' requires';
foreach (explode(',', $element->requires) as $groupName) {
$requiresClass .= ' requires-' . $section->getName() . '_' . $groupName;
}
}
$field = $fieldset->addField($id, $fieldType, array(
'name' => $name,
'label' => $label,
'comment' => $comment,
'tooltip' => $tooltip,
'hint' => $hint,
'value' => $data,
'inherit' => $inherit,
'class' => $element->frontend_class . $sharedClass . $requiresClass,
'field_config' => $element,
'scope' => $this->getScope(),
'scope_id' => $this->getScopeId(),
'scope_label' => $this->getScopeLabel($element),
'can_use_default_value' => $this->canUseDefaultValue((int)$element->show_in_default),
'can_use_website_value' => $this->canUseWebsiteValue((int)$element->show_in_website),
));
$this->_prepareFieldOriginalData($field, $element);
if (isset($element->validate)) {
$field->addClass($element->validate);
}
if (isset($element->frontend_type)
&& 'multiselect' === (string)$element->frontend_type
&& isset($element->can_be_empty)
) {
$field->setCanBeEmpty(true);
}
$field->setRenderer($fieldRenderer);
if ($element->source_model) {
// determine callback for the source model
$factoryName = (string)$element->source_model;
$method = false;
if (preg_match('/^([^:]+?)::([^:]+?)$/', $factoryName, $matches)) {
array_shift($matches);
list($factoryName, $method) = array_values($matches);
}
$sourceModel = Mage::getSingleton($factoryName);
if ($sourceModel instanceof Varien_Object) {
$sourceModel->setPath($path);
}
if ($method) {
if ($fieldType == 'multiselect') {
$optionArray = $sourceModel->$method();
} else {
$optionArray = array();
foreach ($sourceModel->$method() as $value => $label) {
$optionArray[] = array('label' => $label, 'value' => $value);
}
}
} else {
$optionArray = $sourceModel->toOptionArray($fieldType == 'multiselect');
}
$field->setValues($optionArray);
}
}
}
return $this;
}
/**
* Return config root node for current scope
*
* #return Varien_Simplexml_Element
*/
public function getConfigRoot()
{
if (empty($this->_configRoot)) {
$this->_configRoot = Mage::getSingleton('adminhtml/config_data')->getConfigRoot();
}
return $this->_configRoot;
}
/**
* Set "original_data" array to the element, composed from nodes with scalar values
*
* #param Varien_Data_Form_Element_Abstract $field
* #param Varien_Simplexml_Element $xmlElement
*/
protected function _prepareFieldOriginalData($field, $xmlElement)
{
$originalData = array();
foreach ($xmlElement as $key => $value) {
if (!$value->hasChildren()) {
$originalData[$key] = (string)$value;
}
}
$field->setOriginalData($originalData);
}
/**
* Support models "getCommentText" method for field note generation
*
* #param Mage_Core_Model_Config_Element $element
* #param string $helper
* #return string
*/
protected function _prepareFieldComment($element, $helper, $currentValue)
{
$comment = '';
if ($element->comment) {
$commentInfo = $element->comment->asArray();
if (is_array($commentInfo)) {
if (isset($commentInfo['model'])) {
$model = Mage::getModel($commentInfo['model']);
if (method_exists($model, 'getCommentText')) {
$comment = $model->getCommentText($element, $currentValue);
}
}
} else {
$comment = Mage::helper($helper)->__($commentInfo);
}
}
return $comment;
}
/**
* Prepare additional comment for field like tooltip
*
* #param Mage_Core_Model_Config_Element $element
* #param string $helper
* #return string
*/
protected function _prepareFieldTooltip($element, $helper)
{
if ($element->tooltip) {
return Mage::helper($helper)->__((string)$element->tooltip);
} elseif ($element->tooltip_block) {
return $this->getLayout()->createBlock((string)$element->tooltip_block)->toHtml();
}
return '';
}
/**
* Append dependence block at then end of form block
*
*
*/
protected function _afterToHtml($html)
{
if ($this->_getDependence()) {
$html .= $this->_getDependence()->toHtml();
}
$html = parent::_afterToHtml($html);
return $html;
}
/**
* Enter description here...
*
* #param Varien_Simplexml_Element $a
* #param Varien_Simplexml_Element $b
* #return boolean
*/
protected function _sortForm($a, $b)
{
return (int)$a->sort_order < (int)$b->sort_order ? -1 : ((int)$a->sort_order > (int)$b->sort_order ? 1 : 0);
}
/**
* Enter description here...
*
* #param Varien_Simplexml_Element $field
* #return boolean
*/
public function canUseDefaultValue($field)
{
if ($this->getScope() == self::SCOPE_STORES && $field) {
return true;
}
if ($this->getScope() == self::SCOPE_WEBSITES && $field) {
return true;
}
return false;
}
/**
* Enter description here...
*
* #param Varien_Simplexml_Element $field
* #return boolean
*/
public function canUseWebsiteValue($field)
{
if ($this->getScope() == self::SCOPE_STORES && $field) {
return true;
}
return false;
}
/**
* Checking field visibility
*
* #param Varien_Simplexml_Element $field
* #return bool
*/
protected function _canShowField($field)
{
$ifModuleEnabled = trim((string)$field->if_module_enabled);
if ($ifModuleEnabled && !Mage::helper('Core')->isModuleEnabled($ifModuleEnabled)) {
return false;
}
switch ($this->getScope()) {
case self::SCOPE_DEFAULT:
return (int)$field->show_in_default;
break;
case self::SCOPE_WEBSITES:
return (int)$field->show_in_website;
break;
case self::SCOPE_STORES:
return (int)$field->show_in_store;
break;
}
return true;
}
/**
* Retrieve current scope
*
* #return string
*/
public function getScope()
{
$scope = $this->getData('scope');
if (is_null($scope)) {
if ($this->getStoreCode()) {
$scope = self::SCOPE_STORES;
} elseif ($this->getWebsiteCode()) {
$scope = self::SCOPE_WEBSITES;
} else {
$scope = self::SCOPE_DEFAULT;
}
$this->setScope($scope);
}
return $scope;
}
/**
* Retrieve label for scope
*
* #param Mage_Core_Model_Config_Element $element
* #return string
*/
public function getScopeLabel($element)
{
if ($element->show_in_store == 1) {
return $this->_scopeLabels[self::SCOPE_STORES];
} elseif ($element->show_in_website == 1) {
return $this->_scopeLabels[self::SCOPE_WEBSITES];
}
return $this->_scopeLabels[self::SCOPE_DEFAULT];
}
/**
* Get current scope code
*
* #return string
*/
public function getScopeCode()
{
$scopeCode = $this->getData('scope_code');
if (is_null($scopeCode)) {
if ($this->getStoreCode()) {
$scopeCode = $this->getStoreCode();
} elseif ($this->getWebsiteCode()) {
$scopeCode = $this->getWebsiteCode();
} else {
$scopeCode = '';
}
$this->setScopeCode($scopeCode);
}
return $scopeCode;
}
/**
* Get current scope code
*
* #return int|string
*/
public function getScopeId()
{
$scopeId = $this->getData('scope_id');
if (is_null($scopeId)) {
if ($this->getStoreCode()) {
$scopeId = Mage::app()->getStore($this->getStoreCode())->getId();
} elseif ($this->getWebsiteCode()) {
$scopeId = Mage::app()->getWebsite($this->getWebsiteCode())->getId();
} else {
$scopeId = '';
}
$this->setScopeId($scopeId);
}
return $scopeId;
}
/**
* Enter description here...
*
* #return array
*/
protected function _getAdditionalElementTypes()
{
return array(
'export' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_export'),
'import' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_import'),
'allowspecific' => Mage::getConfig()
->getBlockClassName('adminhtml/system_config_form_field_select_allowspecific'),
'image' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_image'),
'file' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_file')
);
}
/**
* Temporary moved those $this->getRequest()->getParam('blabla') from the code accross this block
* to getBlala() methods to be later set from controller with setters
*/
/**
* Enter description here...
*
* #TODO delete this methods when {^see above^} is done
* #return string
*/
public function getSectionCode()
{
return $this->getRequest()->getParam('section', '');
}
/**
* Enter description here...
*
* #TODO delete this methods when {^see above^} is done
* #return string
*/
public function getWebsiteCode()
{
return $this->getRequest()->getParam('website', '');
}
/**
* Enter description here...
*
* #TODO delete this methods when {^see above^} is done
* #return string
*/
public function getStoreCode()
{
return $this->getRequest()->getParam('store', '');
}
}
Guide me how to resolve this.
Thanks in advance
Since you did not provide any code I can break down the basics.
That error means the object is empty.
If your code looked like this for example.
$results->toOptionArray()
Then the error is telling you $results is not an instance of an object.
I need to insert multiple ActiveRecord object in Yii,if all of them inserted
$transaction = Yii::app()->db->beginTransaction();
for ($i = 0;$i < 10;$i++){
$model = new Mymodel();
$model->x = $i;
if (!$model->save()){
$transaction->rollback();
break;
}
}
if ($transaction->active)
$transaction->commit();
Now I need to insert all of them in one query,How can I do it during using active record?
A new version of this class
class CDbMultiInsertCommand extends CDbCommand{
/** #var CActiveRecord $class */
private $class;
/** #var string $insert_template */
private $insert_template = "insert into %s(%s) ";
/** #var string $value_template */
private $value_template = "(%s)";
/** #var string $query */
public $query;
/** #var CDbColumnSchema[] $columns */
private $columns;
/** #var boolean $fresh */
private $fresh;
/** #var CDbConnection $db */
private $db;
/** #param CActiveRecord $class
* #param CDbConnection $db
*/
public function __construct($class, $db = null){
$this->class = $class;
$this->createTemplate();
if(is_null($db)){
$this->db = Yii::app()->db;
}
else{
$this->db = $db;
}
parent::__construct($this->getConnection());
}
private function createTemplate(){
$this->fresh = true;
$value_template = "";
$columns_string = "";
$this->columns = $this->class->getMetaData()->tableSchema->columns;
$counter = 0;
foreach($this->columns as $column){
/** #var CDbColumnSchema $column */
if($column->autoIncrement){
$value_template .= "0";
}
else if($column->type == "integer" || $column->type == "boolean" || $column->type == "float" || $column->type == "double") {
$value_template .= "%d";
}
else{
$value_template .= "\"%s\"";
}
$columns_string .= $column->name;
$counter ++;
if($counter != sizeof($this->columns)){
$columns_string .= ", ";
$value_template .= ", ";
}
}
$this->insert_template = sprintf($this->insert_template, $this->class->tableName(), $columns_string);
$this->value_template = sprintf($this->value_template, $value_template);
}
/** #param boolean $validate
* #param CActiveRecord $record
*/
public function add($record, $validate = true){
$values = array();
if($validate){
if(!$record->validate()){
return false;
}
}
$counter = 0;
foreach($this->columns as $column){
if($column->autoIncrement){
continue;
}
$values[$counter] = $record->{$column->name};
$counter ++;
}
if(!$this->fresh){
$this->query .= ",";
}
else{
$this->query = "values";
}
$this->fresh = false;
$this->query .= vsprintf($this->value_template, $values);
return true;
}
public function getConnection(){
return $this->db;
}
public function execute(){
if(!$this->query)
return;
$this->setText($this->insert_template." ".$this->query);
return parent::execute();
}
}
Usage would be:
$transaction = Yii::app()->db->beginTransaction();
$multi = new CDbMultiInsertCommand(new Mymodel());
for ($i = 0;$i < 10;$i++){
$model = new Mymodel();
$model->x = $i;
$multi->add($model, $shouldBeValidated);
}
$multi->execute();
if ($transaction->active)
$transaction->commit();
While not entirely Yii like, it can be made as an extension/component, and is treated like a normal command, so transactions still apply. It would be entirely possible to set this up to utilise parameters rather than string literals in the query, and could also implement checking of null and default values.
class CDbMultiInsertCommand extends CDbCommand{
/** #var CActiveRecord $class */
private $class;
/** #var string $insert_template */
private $insert_template = "insert into %s(%s) ";
/** #var string $value_template */
private $value_template = "(%s)";
/** #var string $query */
public $query;
/** #var CDbColumnSchema[] $columns */
private $columns;
/** #var boolean $fresh */
private $fresh;
/** #var CDbConnection $db */
private $db;
/** #param CActiveRecord $class
* #param CDbConnection $db
*/
public function __construct($class, $db = null){
$this->class = $class;
$this->createTemplate();
if(is_null($db)){
$this->db = Yii::app()->db;
}
else{
$this->db = $db;
}
}
private function createTemplate(){
$this->fresh = true;
$value_template = "";
$columns_string = "";
$this->columns = $this->class->getMetaData()->tableSchema->columns;
$counter = 0;
foreach($this->columns as $column){
/** #var CDbColumnSchema $column */
if($column->autoIncrement){
$value_template .= "0";
}
else if($column->type == "integer" || $column->type == "boolean" || $column->type == "float" || $column->type == "double") {
$value_template .= "%d";
}
else{
$value_template .= "\"%s\"";
}
$columns_string .= $column->name;
$counter ++;
if($counter != sizeof($this->columns)){
$columns_string .= ", ";
$value_template .= ", ";
}
}
$this->insert_template = sprintf($this->insert_template, $this->class->tableName(), $columns_string);
$this->value_template = sprintf($this->value_template, $value_template);
}
/** #param boolean $validate
* #param CActiveRecord $record
*/
public function add($record, $validate = true){
$values = array();
if($validate){
if(!$record->validate()){
return false;
}
}
$counter = 0;
foreach($this->columns as $column){
if($column->autoIncrement){
continue;
}
$values[$counter] = $this->class->{$column->name};
$counter ++;
}
if(!$this->fresh){
$this->query .= ",";
}
else{
$this->query = "values";
}
$this->fresh = false;
$this->query .= vsprintf($this->value_template, $values);
return true;
}
public function getConnection(){
return $this->db;
}
public function execute(){
$this->setText($this->insert_template." ".$this->query);
return parent::execute();
}
}
Usage would be:
$transaction = Yii::app()->db->beginTransaction();
$multi = new CDbMultiInsertCommand(new Mymodel());
for ($i = 0;$i < 10;$i++){
$model = new Mymodel();
$model->x = $i;
$multi->add($model, $shouldBeValidated);
}
$multi->execute();
if ($transaction->active)
$transaction->commit();
Of course it could be made more elaborate and extended to allow for updates, etc
Hope this helps.
Since Yii 1.1.14 there is CDbCommandBuilder::createMultipleInsertCommand() method available. If you need to insert multiple records in one query, you should probably use it, since all other answers in this question are vulnerable to SQL injection, so it is easy to mess up something if you're trying to implement something like that by yourself.
Yii::app()->db->getCommandBuilder()
->createMultipleInsertCommand('table_name', $data)
->execute();
For array of models you can probably generate $data in this way (note that it will not make any validation):
$data = [];
foreach ($models as $model) {
$data[] = $model->getAttributes();
}
Update for the Bulk Insert / Batch Insert for YII
class CDbMultiInsertCommand extends CDbCommand{
/** #var CActiveRecord $class */
private $class;
/** #var string $insert_template */
private $insert_template = "insert into %s(%s) ";
/** #var string $value_template */
private $value_template = "(%s)";
/** #var string $query */
public $query;
/** #var CDbColumnSchema[] $columns */
private $columns;
/** #var boolean $fresh */
private $fresh;
/** #var CDbConnection $db */
private $db;
/** #param CActiveRecord $class
* #param CDbConnection $db
*/
public function __construct($class, $db = null){
$this->class = $class;
$this->createTemplate();
if(is_null($db)){
$this->db = Yii::app()->db;
}
else{
$this->db = $db;
}
parent::__construct($this->getConnection());
}
private function createTemplate(){
$this->fresh = true;
$value_template = "";
$columns_string = "";
$this->columns = $this->class->getMetaData()->tableSchema->columns;
$counter = 0;
foreach($this->columns as $keyColumnName => $column){
/** #var CDbColumnSchema $column */
if($column->autoIncrement){
unset($this->columns[$keyColumnName]);
continue;
// $value_template .= "0";
}
else if($column->type == "integer" || $column->type == "boolean" || $column->type == "float" || $column->type == "double") {
$value_template .= "%d";
}
else{
$value_template .= "\"%s\"";
}
$columns_string .= '"'.$column->name.'"';
$counter ++;
if($counter != sizeof($this->columns)){
$columns_string .= ", ";
$value_template .= ", ";
}
}
$this->insert_template = sprintf($this->insert_template, $this->class->tableName(), $columns_string);
$this->value_template = sprintf($this->value_template, $value_template);
}
/** #param boolean $validate
* #param CActiveRecord $record
*/
public function add($record, $validate = true){
$values = array();
if($validate){
if(!$record->validate()){
return false;
}
}
$counter = 0;
foreach($this->columns as $column){
if($column->autoIncrement){
continue;
}
$values[$counter] = $record->{$column->name};
$counter ++;
}
if(!$this->fresh){
$this->query .= ",";
}
else{
$this->query = "values";
}
$this->fresh = false;
$this->query .= vsprintf($this->value_template, $values);
$this->query = str_replace('"', "'", $this->query);
return true;
}
public function getConnection(){
return $this->db;
}
public function execute($params=array()){
if(!$this->query)
return;
$this->setText($this->insert_template." ".$this->query);
return parent::execute();
}
}
I was facing problem with 3 things with the earlier code.
Auto increment column where in earlier code it was set as 0
Query statement which had double quotes.
execute function should be similar to parent execute function with parameter.
I guess the first 2 points are related to database I am using postgresql, hope the updated code works for all database systems.
I have the below code that creates a custom menu in Magento:
<?php
/**
* Catalog navigation
*/
class Infortis_Ultimo_Block_Navigation extends Mage_Core_Block_Template
{
//NEW:
protected $_isAccordion = FALSE;
protected $_categoryInstance = null;
/**
* Current category key
*
* #var string
*/
protected $_currentCategoryKey;
/**
* Array of level position counters
*
* #var array
*/
protected $_itemLevelPositions = array();
protected function _construct()
{
$this->addData(array(
'cache_lifetime' => false,
'cache_tags' => array(Mage_Catalog_Model_Category::CACHE_TAG, Mage_Core_Model_Store_Group::CACHE_TAG),
));
}
/**
* Get Key pieces for caching block content
*
* #return array
*/
public function getCacheKeyInfo()
{
$shortCacheId = array(
'CATALOG_NAVIGATION',
Mage::app()->getStore()->getId(),
Mage::getDesign()->getPackageName(),
Mage::getDesign()->getTheme('template'),
Mage::getSingleton('customer/session')->getCustomerGroupId(),
'template' => $this->getTemplate(),
'name' => $this->getNameInLayout(),
$this->getCurrenCategoryKey()
);
$cacheId = $shortCacheId;
$shortCacheId = array_values($shortCacheId);
$shortCacheId = implode('|', $shortCacheId);
$shortCacheId = md5($shortCacheId);
$cacheId['category_path'] = $this->getCurrenCategoryKey();
$cacheId['short_cache_id'] = $shortCacheId;
return $cacheId;
}
/**
* Get current category key
*
* #return mixed
*/
public function getCurrenCategoryKey()
{
if (!$this->_currentCategoryKey) {
$category = Mage::registry('current_category');
if ($category) {
$this->_currentCategoryKey = $category->getPath();
} else {
$this->_currentCategoryKey = Mage::app()->getStore()->getRootCategoryId();
}
}
return $this->_currentCategoryKey;
}
/**
* Get catagories of current store
*
* #return Varien_Data_Tree_Node_Collection
*/
public function getStoreCategories()
{
$helper = Mage::helper('catalog/category');
return $helper->getStoreCategories();
}
/**
* Retrieve child categories of current category
*
* #return Varien_Data_Tree_Node_Collection
*/
public function getCurrentChildCategories()
{
$layer = Mage::getSingleton('catalog/layer');
$category = $layer->getCurrentCategory();
/* #var $category Mage_Catalog_Model_Category */
$categories = $category->getChildrenCategories();
$productCollection = Mage::getResourceModel('catalog/product_collection');
$layer->prepareProductCollection($productCollection);
$productCollection->addCountToCategories($categories);
return $categories;
}
/**
* Checkin activity of category
*
* #param Varien_Object $category
* #return bool
*/
public function isCategoryActive($category)
{
if ($this->getCurrentCategory()) {
return in_array($category->getId(), $this->getCurrentCategory()->getPathIds());
}
return false;
}
protected function _getCategoryInstance()
{
if (is_null($this->_categoryInstance)) {
$this->_categoryInstance = Mage::getModel('catalog/category');
}
return $this->_categoryInstance;
}
/**
* Get url for category data
*
* #param Mage_Catalog_Model_Category $category
* #return string
*/
public function getCategoryUrl($category)
{
if ($category instanceof Mage_Catalog_Model_Category) {
$url = $category->getUrl();
} else {
$url = $this->_getCategoryInstance()
->setData($category->getData())
->getUrl();
}
return $url;
}
/**
* Return item position representation in menu tree
*
* #param int $level
* #return string
*/
protected function _getItemPosition($level)
{
if ($level == 0) {
$zeroLevelPosition = isset($this->_itemLevelPositions[$level]) ? $this->_itemLevelPositions[$level] + 1 : 1;
$this->_itemLevelPositions = array();
$this->_itemLevelPositions[$level] = $zeroLevelPosition;
} elseif (isset($this->_itemLevelPositions[$level])) {
$this->_itemLevelPositions[$level]++;
} else {
$this->_itemLevelPositions[$level] = 1;
}
$position = array();
for($i = 0; $i <= $level; $i++) {
if (isset($this->_itemLevelPositions[$i])) {
$position[] = $this->_itemLevelPositions[$i];
}
}
return implode('-', $position);
}
/**
* Render category to html
*
* #param Mage_Catalog_Model_Category $category
* #param int Nesting level number
* #param boolean Whether ot not this item is last, affects list item class
* #param boolean Whether ot not this item is first, affects list item class
* #param boolean Whether ot not this item is outermost, affects list item class
* #param string Extra class of outermost list items
* #param string If specified wraps children list in div with this class
* #param boolean Whether ot not to add on* attributes to list item
* #return string
*/
protected function _renderCategoryMenuItemHtml($category, $level = 0, $isLast = false, $isFirst = false,
$isOutermost = false, $outermostItemClass = '', $childrenWrapClass = '', $noEventAttributes = false)
{
if (!$category->getIsActive()) {
return '';
}
$html = array();
// get all children
if (Mage::helper('catalog/category_flat')->isEnabled()) {
$children = (array)$category->getChildrenNodes();
$childrenCount = count($children);
} else {
$children = $category->getChildren();
$childrenCount = $children->count();
}
$hasChildren = ($children && $childrenCount);
// select active children
$activeChildren = array();
foreach ($children as $child) {
if ($child->getIsActive()) {
$activeChildren[] = $child;
}
}
$activeChildrenCount = count($activeChildren);
$hasActiveChildren = ($activeChildrenCount > 0);
// prepare list item html classes
$classes = array();
$classes[] = 'level' . $level;
$classes[] = 'nav-' . $this->_getItemPosition($level);
if ($this->isCategoryActive($category)) {
$classes[] = 'active';
}
$linkClass = '';
if ($isOutermost && $outermostItemClass) {
$classes[] = $outermostItemClass;
$linkClass = ' class="'.$outermostItemClass.'"';
}
if ($isFirst) {
$classes[] = 'first';
}
if ($isLast) {
$classes[] = 'last';
}
if ($hasActiveChildren) {
$classes[] = 'parent';
}
//NEW: add special class if level == 1 and menu is not an accordion.
if ($this->_isAccordion == FALSE && $level == 1) {
$classes[] = 'item';
}
// prepare list item attributes
$attributes = array();
if (count($classes) > 0) {
$attributes['class'] = implode(' ', $classes);
}
if ($hasActiveChildren && !$noEventAttributes) {
$attributes['onmouseover'] = 'toggleMenu(this,1)';
$attributes['onmouseout'] = 'toggleMenu(this,0)';
}
// assemble list item with attributes
$htmlLi = '<li';
foreach ($attributes as $attrName => $attrValue) {
$htmlLi .= ' ' . $attrName . '="' . str_replace('"', '\"', $attrValue) . '"';
}
$htmlLi .= '>';
$html[] = $htmlLi;
if ($level == 0 && $hasChildren) {
$html[] = '<a href="javascript:void(0)"'.$linkClass.'>';
$html[] = '<span>' . $this->escapeHtml($category->getName()) . '</span>';
$html[] = '</a>';
}
else {
$html[] = '<a href="'.$this->getCategoryUrl($category).'"'.$linkClass.'>';
$html[] = '<span>' . $this->escapeHtml($category->getName()) . '</span>';
$html[] = '</a>';
}
// render children
$htmlChildren = '';
$j = 0;
foreach ($activeChildren as $child) {
$htmlChildren .= $this->_renderCategoryMenuItemHtml(
$child,
($level + 1),
($j == $activeChildrenCount - 1),
($j == 0),
false,
$outermostItemClass,
$childrenWrapClass,
$noEventAttributes
);
$j++;
}
if (!empty($htmlChildren)) {
//NEW: add opener if menu is used as accordion.
if ($this->_isAccordion == TRUE)
$html[] = '<span class="opener"> </span>';
if ($childrenWrapClass) {
$html[] = '<div class="' . $childrenWrapClass . '">';
}
$html[] = '<ul class="level' . $level . '">';
$html[] = $htmlChildren;
$html[] = '</ul>';
if ($childrenWrapClass) {
$html[] = '</div>';
}
}
$html[] = '</li>';
$html = implode("\n", $html);
return $html;
}
/**
* Render category to html
*
* #deprecated deprecated after 1.4
* #param Mage_Catalog_Model_Category $category
* #param int Nesting level number
* #param boolean Whether ot not this item is last, affects list item class
* #return string
*/
public function drawItem($category, $level = 0, $last = false)
{
return $this->_renderCategoryMenuItemHtml($category, $level, $last);
}
/**
* Enter description here...
*
* #return Mage_Catalog_Model_Category
*/
public function getCurrentCategory()
{
if (Mage::getSingleton('catalog/layer')) {
return Mage::getSingleton('catalog/layer')->getCurrentCategory();
}
return false;
}
/**
* Enter description here...
*
* #return string
*/
public function getCurrentCategoryPath()
{
if ($this->getCurrentCategory()) {
return explode(',', $this->getCurrentCategory()->getPathInStore());
}
return array();
}
/**
* Enter description here...
*
* #param Mage_Catalog_Model_Category $category
* #return string
*/
public function drawOpenCategoryItem($category) {
$html = '';
if (!$category->getIsActive()) {
return $html;
}
$html.= '<li';
if ($this->isCategoryActive($category)) {
$html.= ' class="active"';
}
$html.= '>'."\n";
$html.= '<span>'.$this->htmlEscape($category->getName()).'</span>'."\n";
if (in_array($category->getId(), $this->getCurrentCategoryPath())){
$children = $category->getChildren();
$hasChildren = $children && $children->count();
if ($hasChildren) {
$htmlChildren = '';
foreach ($children as $child) {
$htmlChildren.= $this->drawOpenCategoryItem($child);
}
if (!empty($htmlChildren)) {
$html.= '<ul>'."\n"
.$htmlChildren
.'</ul>';
}
}
}
$html.= '</li>'."\n";
return $html;
}
/**
* Render categories menu in HTML
*
* #param bool Add opener if menu is used as accordion.
* #param int Level number for list item class to start from
* #param string Extra class of outermost list items
* #param string If specified wraps children list in div with this class
* #return string
*/
public function renderCategoriesMenuHtml($isAccordion = FALSE, $level = 0, $outermostItemClass = '', $childrenWrapClass = '')
{
//NEW: save additional attribute
$this->_isAccordion = $isAccordion;
$activeCategories = array();
foreach ($this->getStoreCategories() as $child) {
if ($child->getIsActive()) {
$activeCategories[] = $child;
}
}
$activeCategoriesCount = count($activeCategories);
$hasActiveCategoriesCount = ($activeCategoriesCount > 0);
if (!$hasActiveCategoriesCount) {
return '';
}
$html = '';
$j = 0;
foreach ($activeCategories as $category) {
$html .= $this->_renderCategoryMenuItemHtml(
$category,
$level,
($j == $activeCategoriesCount - 1),
($j == 0),
true,
$outermostItemClass,
$childrenWrapClass,
true
);
$j++;
}
return $html;
}
}
I would like to add a custom category attribute (menu_label) to the menu items. I have created the custom category attribute using this tutorial http://www.atwix.com/magento/add-category-attribute/
The attribute shows up fine in admin and I can get it to print out on my normal template files but can't get it to show in this menu.
I thought $this->escapeHtml($category->getMenuLabel()) would have done it but this doesn't output anything.
Any ideas?
You have to consider the fact that Magento is not acting the same with flat categories enable or disable.
I suppose you may be with flat category enabled, in your case, because it should work otherwise.
(Please check in System > Configuration > Catalog > Catalog > Frontend the field Use Flat Catalog Category. If it is set to Yes, then that is where your problem is.)
To solve it add this to your config.xml in the frontend node:
<events>
<catalog_category_flat_loadnodes_before>
<observers>
<somemodule>
<type>singleton</type>
<class>somemodule/observer</class>
<method>addMenuAttributes</method>
</somemodule>
</observers>
</catalog_category_flat_loadnodes_before>
</events>
Then create an Observer.php in the Model folder of your module (the model folder should be declared in your config.xml too, of course).
Here is the observer code:
<?php
class Somecompany_Somemodule_Model_Observer {
public function addMenuAttributes(Varien_Event_Observer $observer) {
$observer->getSelect()->columns(
array('menu_label')
);
}
}
You assumtion is incorrect:
$this->escapeHtml($category->getMenuLabel())
This assumes $category is indeed a Category Model (Mage_Catalog_Model_category) when infact it's not, it's a Node object.
if you look here:
Mage_Catalog_Model_Observer::_addCategoriesToMenu()
You will notice where the actual catalog model is used to create an array which is passed to the Navigation routine as a Varien_Data_Tree_Node.
You can add in your custom attribute here, and then access it inside the block.
$categoryData = array(
'name' => $category->getName(),
'id' => $nodeId,
'url' => Mage::helper('catalog/category')->getCategoryUrl($category),
'is_active' => $this->_isActiveMenuCategory($category),
'my_attribute' => $category->getData('my_attribute')
);
You will then be able to access the attribute inside your custom menu block:
$child->getData('my_attribute');
//$this->escapeHtml($category->getData('my_attribute'))
I want to build advanced search script but I have this error with search_all function in the model
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysql_result could not be converted to string
Filename: models/search_model.php
Line Number: 129
i have four fildes
1- input text to write the book name
2- select box for the author
3- select box for the publisher
3-select box for the section
the model is
class search_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
/* This function get all search in database sort by order asc.*/
function get_new_one($id)
{
$this->db->where('ne_id',$id);
$result=$this->db->get('d_search');
return $result->row();
}
//////////////frontend//////////////////////////////////////////////////////////
function show_new($id)
{
$result=$this->db->query("SELECT * , COUNT( d_comments_search.cn_new_id ) as count
FROM d_search
left JOIN d_comments_search ON d_search.ne_id = d_comments_search.cn_new_id and d_search.ne_hide='1'
inner join d_search_category on d_search_category.nc_id = d_search.ne_category_id and d_search_category.nc_hide= '1'
and d_search.ne_id= $id group by d_search.ne_id");
return $result->row() ;
}
function generate_results($keyword,$row=0){
$result1 = $this->db->query("SELECT bo_id,bo_name,bo_state,bo_about FROM d_book where (bo_name like '%$keyword%' or bo_about like '%$keyword%') and bo_state = '1' limit $row,20");
$result2 = $this->db->query("SELECT au_id,au_name,au_state,au_info FROM d_author where (au_name like '%$keyword%' or au_info like '%$keyword%') and au_state = '1' limit $row,20");
$result3 = $this->db->query("SELECT pub_id,pub_name,pub_state,pub_info FROM d_publishing where (pub_name like '%$keyword%' or pub_info like '%$keyword%') and pub_state = '1' limit $row,20");
$results = array_merge($result1->result_array(),$result2->result_array(),$result3->result_array());
return $results;
}
// get total number of users
function getNumUsers($keyword)
{
$result1 = $this->db->query("SELECT bo_id,bo_name,bo_state,bo_about FROM d_book where (bo_name like '%$keyword%' or bo_about like '%$keyword%') and bo_state = '1'");
$result1 = $result1->num_rows();
$result2 = $this->db->query("SELECT au_id,au_name,au_state,au_info FROM d_author where (au_name like '%$keyword%' or au_info like '%$keyword%') and au_state = '1'");
$result2 = $result2->num_rows();
$result3 = $this->db->query("SELECT pub_id,pub_name,pub_state,pub_info FROM d_publishing where (pub_name like '%$keyword%' or pub_info like '%$keyword%') and pub_state = '1'");
$result3 = $result3->num_rows();
return $result1 + $result2 + $result3;
}
//////////////////////////////////end paging///////////////////
function get_publishing()
{
$this->db->where('pub_state','1');
$result=$this->db->get('d_publishing')->result_array();
return $result;
}
function get_author()
{
$this->db->where('au_state','1');
$result=$this->db->get('d_author')->result_array();
return $result;
}
function get_section()
{
$this->db->where('sec_state','1');
$result=$this->db->get('d_section')->result_array();
return $result;
}
function search_name()
{
$bo_name=$_POST['bo_name'];
$this->db->order_by("bo_ord","asc");
$this->db->like('bo_name',$bo_name);
return $this->db->get('d_book')->result_array();
}
function search_all() {
$publish = $this->input->post('publish');
$author = $this->input->post('author');
$sec_name = $this->input->post('section');
$sql = $this->db->query("SELECT * FROM `d_book`");
$searches = array();
if ($publish != 'choose')
$searches[] = "`bo_pub_id` = '$publish'";
if ($author != 'choose')
$searches[] = "`bo_au_id` = '$author'";
if ($sec_name != 'choose')
$searches[] = "`bo_sec_id` = '$sec_name'";
if (count($searches) > 0) {
$sql .= "WHERE " . implode(" AND ", $searches);
}
$sql .= ';';
}
}
this is controller
class Search extends front_end {
var $temp;
function __construct(){
parent::__construct();
$this->load->library('form_validation');
//echo $this->input->post("keyboard");
}
public function index()
{
$this->overview();
}
/**
* This function display all search
* #param integer $row
*/
public function overview($row=0)
{
$this->form_validation->set_rules('keyword', 'كلمة البØØ«', 'trim|required|xss_clean|htmlspecialchars');
$this->form_validation->run();
$this->store_keyword();
//echo $this->session->flashdata('keyword');
if ($this->session->flashdata('keyword') != ''){
$keyword=$this->session->flashdata('keyword');
$this->generate_results($this->session->flashdata('keyword'),$row);
}else{
$this->generate_results($this->input->post("keyword"),$row);
}
//$this->session->set_flashdata('keyword', $this->input->post("keyword"));
$data = $this->temp;
//$this->session->keep_flashdata('keyword');
$this->view('search/site/results', $data);
}
/**
* This function generate result of search
* #param string $keyword
* #param integer $row
*/
public function generate_results($keyword,$row=0){
$this->load->model('search/search_model','search');
$this->load->library('pagination');
$config['base_url'] = base_url().'search/search/overview/';
$config['total_rows'] = $this->search->getNumUsers($keyword);
$config['per_page'] = '20';
$config['uri_segment'] = '4';
$this->pagination->initialize($config);
$data['page'] = $row;
$data['results'] = $this->search->generate_results($keyword,$row);
$data['total_rows'] = $this->search->getNumUsers($keyword);
$data['links']=$this->pagination->create_links();
$this->temp = $data;
}
/**
* This function display detail of new
* #param integer $id
*/
public function show($id)
{
$data['new']=$this->search->show_new($id);
$count=$data['new']->ne_count_visit;
$this->search->add_count($count,$id);
$data['comments']=$this->search->show_comments($id);
$this->view('site/new', $data);
}
/**
* This function store keyword to use in search
*/
private function store_keyword(){
if($this->input->post("keyword")){
$this->session->set_userdata('keyword', $this->input->post("keyword"));
}
}
public function search_form()
{
$this->load->model('search/search_model','search');
$data['publish']=$this->search->get_publishing();
$data['author']=$this->search->get_author();
$data['section']=$this->search->get_section();
$this->view('search/site/adv_search_form',$data);
}
public function search_adv()
{
$this->load->model('search/search_model','search');
$data['bo_name']=$this->input->post('bo_name');
$data['section']=$this->input->post('section');
$data['publish']=$this->input->post('publish');
$data['author']=$this->input->post('author');
$data['result1'] = '';
$data['result2'] = '';
$data['result3'] = '';
$data['result4'] = '';
if($data['bo_name'] == NULL and $data['section']== NULL and $data['publish']==NULL and $data['author']== NULL){
$this->search_form();
}else{
if(isset($data['bo_name']) and $data['bo_name']!= NULL)
{
$data['result1'] = $this->search->search_name();
}
if(isset($data['section']) and $data['section'] != NULL)
{
$data['result2']=$this->search->search_all();
}
if(isset($data['publish']) and $data['publish'] != NULL)
{
$data['result3']=$this->search->search_all();
}
if(isset($data['author']) and $data['author']!= NULL)
{
$data['result4']=$this->search->search_all();
}
$data['no_results'] = '';
if(! $data['result1'] && !$data['result2'] && !$data['result3'] && !$data['result4']){
$data['no_results'] = TRUE;
}else{
$data['no_results'] = FALSE;
}
$this->view('search/site/search_result',$data);
}
}
}
/* End of file dashboard.php */
$this->db->query() doesn't store a query string for later use. It actually executes the query right away and return an object of CI_DB_mysql_result. You should build the query string before you call $this->db->query() and store it into a variable, then pass it into the method.
$sql = "SELECT * FROM `d_book` ";
$searches = array();
if ($publish != 'choose')
{
$searches[] = "`bo_pub_id` = '__some_id__'";
}
if ($author != 'choose')
{
$searches[] = "`bo_au_id` = '__some_id__'";
}
if ($sec_name != 'choose')
{
$searches[] = "`bo_sec_id` = '__some_id__'";
}
if (count($searches) > 0)
{
$sql .= "WHERE " . implode(" AND ", $searches);
}
$sql .= ';';
$this->db->query($sql);