Magento 2 : Allow customer to edit custom options on Cart - php

I am trying to add functionality to allow a customer to edit options.
I have created a Module Vendor/COptions.
This is loading custom options and select, however is not getting user selected options.
I would like to know how to received selected options and check if the option is selected.
At the moment this line in Select.php is not receiving anything, and the variable $checked is null.
$configValue = $this->getProduct()->getPreconfiguredValues()->getData('options/' . $_option->getId());
in Vendor/COptions\view\frontend\templates\cart\item\default.phtml :
<?php $selectedOptions = $block->getSelectedOptionList(); ?>
<?php //$_options = Mage::helper('core')->decorateArray($block>getOptions())
$_options = $block->getOptions() ?>
<?php if ($_options AND count($_options)):?>
<dl>
<?php foreach($_options as $_option): ?>
<?php echo $this->getOptionHtml($_option) ?>
<?php endforeach; ?>
</dl>
<?php endif; ?>
in Vendor\COptions\Helper\Rewrite\Product:
public function getCustomOptions(\Magento\Catalog\Model\Product\Configuration\Item\ItemInterface $item, $simple="")
{
$product = $item->getProduct();
$coptions = [];
$coptions = $product->getOptions();
$options = array();
if ($coptions) {
foreach ($coptions as $option) {
$itemOption = $item->getOptionByCode('option_' . $option->getId());
/** #var $group \Magento\Catalog\Model\Product\Option\Type\DefaultType */
$group = $option->groupFactory($option->getType())
->setOption($option)
->setConfigurationItem($item)
->setConfigurationItemOption($itemOption);
if ('file' == $option->getType()) {
$downloadParams = $item->getFileDownloadParams();
if ($downloadParams) {
$url = $downloadParams->getUrl();
if ($url) {
$group->setCustomOptionDownloadUrl($url);
}
$urlParams = $downloadParams->getUrlParams();
if ($urlParams) {
$group->setCustomOptionUrlParams($urlParams);
}
}
}
if($simple == "Y"){
array_push($options, $itemOption['value']);
}else{
$options[] = [
'label' => $option->getTitle(),
'value' => $group->getFormattedOptionValue($itemOption['value']),
'print_value' => $group->getFormattedOptionValue($itemOption['value']),
'option_id' => $option->getId(),
'option_type' => $option->getType(),
'custom_view' => $group->isCustomizedView(),
];
}
}
}
$addOptions = $item->getOptionByCode('additional_options');
if ($addOptions) {
$options = array_merge($options, $this->serializer->unserialize($addOptions->getValue()));
}
return $options;
}
in Vendor/COptions\Block\Rewrite\Catalog\Product\View\Options\Type\Select.php:
public function getValuesHtml()
{
$_option = $this->getOption();
$configValue = $this->getProduct()->getPreconfiguredValues()->getData('options/' . $_option->getId());
$store = $this->getProduct()->getStore();
$this->setSkipJsReloadPrice(1);
// Remove inline prototype onclick and onchange events
if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN ||
$_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE
) {
$require = $_option->getIsRequire() ? ' required' : '';
$extraParams = '';
$select = $this->getLayout()->createBlock(
\Magento\Framework\View\Element\Html\Select::class
)->setData(
[
'id' => 'select_' . $_option->getId(),
'class' => $require . ' product-custom-option admin__control-select'
]
);
if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN) {
$select->setName('options[' . $_option->getid() . ']')->addOption('', __('-- Please Select --'));
} else {
$select->setName('options[' . $_option->getid() . '][]');
$select->setClass('multiselect admin__control-multiselect' . $require . ' product-custom-option');
}
foreach ($_option->getValues() as $_value) {
$priceStr = $this->_formatPrice(
[
'is_percent' => $_value->getPriceType() == 'percent',
'pricing_value' => $_value->getPrice($_value->getPriceType() == 'percent'),
],
false
);
$select->addOption(
$_value->getOptionTypeId(),
$_value->getTitle() . ' ' . strip_tags($priceStr) . '',
['price' => $this->pricingHelper->currencyByStore($_value->getPrice(true), $store, false)]
);
}
if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE) {
$extraParams = ' multiple="multiple"';
}
if (!$this->getSkipJsReloadPrice()) {
$extraParams .= ' onchange="opConfig.reloadPrice()"';
}
$extraParams .= ' data-selector="' . $select->getName() . '"';
$select->setExtraParams($extraParams);
if ($configValue) {
$select->setValue($configValue);
}
return $select->getHtml();
}
if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_RADIO ||
$_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX
) {
$selectHtml = '<div class="options-list nested" id="options-' . $_option->getId() . '-list">';
$require = $_option->getIsRequire() ? ' required' : '';
$arraySign = '';
switch ($_option->getType()) {
case \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_RADIO:
$type = 'radio';
$class = 'radio admin__control-radio';
if (!$_option->getIsRequire()) {
$selectHtml .= '<div class="field choice admin__field admin__field-option">' .
'<input type="radio" id="options_' .
$_option->getId() .
'" class="' .
$class .
' product-custom-option" name="options[' .
$_option->getId() .
']"' .
' data-selector="options[' . $_option->getId() . ']"' .
($this->getSkipJsReloadPrice() ? '' : ' onclick="opConfig.reloadPrice()"') .
' value="" checked="checked" /><label class="label admin__field-label" for="options_' .
$_option->getId() .
'"><span>' .
__('None') . '</span></label></div>';
}
break;
case \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX:
$type = 'checkbox';
$class = 'checkbox admin__control-checkbox';
$arraySign = '[]';
break;
}
$count = 1;
foreach ($_option->getValues() as $_value) {
$count++;
$priceStr = $this->_formatPrice(
[
'is_percent' => $_value->getPriceType() == 'percent',
'pricing_value' => $_value->getPrice($_value->getPriceType() == 'percent'),
]
);
$htmlValue = $_value->getOptionTypeId();
if ($arraySign) {
$checked = is_array($configValue) && in_array($htmlValue, $configValue) ? 'checked' : '';
} else {
$checked = $configValue == $htmlValue ? 'checked' : '';
}
$dataSelector = 'options[' . $_option->getId() . ']';
if ($arraySign) {
$dataSelector .= '[' . $htmlValue . ']';
}
$selectHtml .= '<div class="field choice admin__field admin__field-option' .
$require .
'">' .
'<input type="' .
$type .
'" class="' .
$class .
' ' .
$require .
' product-custom-option"' .
($this->getSkipJsReloadPrice() ? '' : ' onclick="opConfig.reloadPrice()"') .
' name="options[' .
$_option->getId() .
']' .
$arraySign .
'" id="options_' .
$_option->getId() .
'_' .
$count .
'" value="' .
$htmlValue .
'" ' .
$checked .
' data-selector="' . $dataSelector . '"' .
' price="' .
$this->pricingHelper->currencyByStore($_value->getPrice(true), $store, false) .
'" />' .
'<label class="label admin__field-label" for="options_' .
$_option->getId() .
'_' .
$count .
'"><span>' .
$_value->getTitle() .
'</span> ' .
$priceStr .
'</label>';
$selectHtml .= '</div>';
}
$selectHtml .= '</div>';
return $selectHtml;
}
}

Related

How to add a new line in textarea element in php code?

I want to add a newline in a textarea. I tried with < p> tag but it's not working. Can you help me to insert a newline in a textarea? Please find the code above for a generic contact form. Where should I add tags for line breaks here?
public function cs_form_textarea_render($params = '') {
global $post, $pagenow;
extract($params);
if ( $pagenow == 'post.php' ) {
$cs_value = get_post_meta($post->ID, 'cs_' . $id, true);
} else {
$cs_value = $std;
}
if ( isset($cs_value) && $cs_value != '' ) {
$value = $cs_value;
} else {
$value = $std;
}
$cs_rand_id = time();
if ( isset($force_std) && $force_std == true ) {
$value = $std;
}
$html_id = ' id="cs_' . sanitize_html_class($id) . '"';
$html_name = ' name="cs_' . sanitize_html_class($id) . '"';
if ( isset($array) && $array == true ) {
$html_id = ' id="cs_' . sanitize_html_class($id) . $cs_rand_id . '"';
$html_name = ' name="cs_' . sanitize_html_class($id) . '_array[]"';
}
$cs_required = '';
if ( isset($required) && $required == 'yes' ) {
$cs_required = ' required="required"';
}
$cs_output = '<div class="' . $classes . '">';
$cs_output .= ' <textarea' . $cs_required . ' rows="5" cols="30"' . $html_id . $html_name . ' placeholder="' . $name . '">' . sanitize_text_field($value) . '</textarea>';
$cs_output .= $this->cs_form_description($description);
$cs_output .= '</div>';
if ( isset($return) && $return == true ) {
return force_balance_tags($cs_output);
} else {
echo force_balance_tags($cs_output);
}
}
Just add a "\n" char somewhere between your text area tags
$cs_output .= ' <textarea' . $cs_required . ' rows="5" cols="30"' . $html_id . $html_name . ' placeholder="' . $name . '">' . sanitize_text_field($value) . "\n" . "this text is on a new line". '</textarea>';
You will try to add "\n" before your end position of the tag. You need to concatenate Like ."\n".

I have some problem with send and write array in database (Codeingniter 3)

I have a form that sends customer data to the database, I added a choice of another category of customers through the input, and instead of sending the data in text, a number is sent.
db
In View
<?php echo render_select('sellers',get_sellers(),array('articleid','subject'),''); ?>
echo render_select helper:
function render_select($name, $options, $option_attrs = [], $label = '', $selected = '', $select_attrs = [], $form_group_attr = [], $form_group_class = '', $select_class = '', $include_blank = true)
{
$callback_translate = '';
if (isset($options['callback_translate'])) {
$callback_translate = $options['callback_translate'];
unset($options['callback_translate']);
}
$select = '';
$_form_group_attr = '';
$_select_attrs = '';
if (!isset($select_attrs['data-width'])) {
$select_attrs['data-width'] = '100%';
}
if (!isset($select_attrs['data-none-selected-text'])) {
$select_attrs['data-none-selected-text'] = _l('dropdown_non_selected_tex');
}
foreach ($select_attrs as $key => $val) {
// tooltips
if ($key == 'title') {
$val = _l($val);
}
$_select_attrs .= $key . '=' . '"' . $val . '" ';
}
$_select_attrs = rtrim($_select_attrs);
$form_group_attr['app-field-wrapper'] = $name;
foreach ($form_group_attr as $key => $val) {
// tooltips
if ($key == 'title') {
$val = _l($val);
}
$_form_group_attr .= $key . '=' . '"' . $val . '" ';
}
$_form_group_attr = rtrim($_form_group_attr);
if (!empty($select_class)) {
$select_class = ' ' . $select_class;
}
if (!empty($form_group_class)) {
$form_group_class = ' ' . $form_group_class;
}
$select .= '<div class="select-placeholder form-group' . $form_group_class . '" ' . $_form_group_attr . '>';
if ($label != '') {
$select .= '<label for="' . $name . '" class="control-label">' . _l($label, '', false) . '</label>';
}
$select .= '<select id="' . $name . '" name="' . $name . '" class="selectpicker' . $select_class . '" ' . $_select_attrs . ' data-live-search="true">';
if ($include_blank == true) {
$select .= '<option value=""></option>';
}
foreach ($options as $option) {
$val = '';
$_selected = '';
$key = '';
if (isset($option[$option_attrs[0]]) && !empty($option[$option_attrs[0]])) {
$key = $option[$option_attrs[0]];
}
if (!is_array($option_attrs[1])) {
$val = $option[$option_attrs[1]];
} else {
foreach ($option_attrs[1] as $_val) {
$val .= $option[$_val] . ' ';
}
}
$val = trim($val);
if ($callback_translate != '') {
if (function_exists($callback_translate) && is_callable($callback_translate)) {
$val = call_user_func($callback_translate, $key);
}
}
$data_sub_text = '';
if (!is_array($selected)) {
if ($selected != '') {
if ($selected == $key) {
$_selected = ' selected';
}
}
} else {
foreach ($selected as $id) {
if ($key == $id) {
$_selected = ' selected';
}
}
}
if (isset($option_attrs[2])) {
if (strpos($option_attrs[2], ',') !== false) {
$sub_text = '';
$_temp = explode(',', $option_attrs[2]);
foreach ($_temp as $t) {
if (isset($option[$t])) {
$sub_text .= $option[$t] . ' ';
}
}
} else {
if (isset($option[$option_attrs[2]])) {
$sub_text = $option[$option_attrs[2]];
} else {
$sub_text = $option_attrs[2];
}
}
$data_sub_text = ' data-subtext=' . '"' . $sub_text . '"';
}
$data_content = '';
if (isset($option['option_attributes'])) {
foreach ($option['option_attributes'] as $_opt_attr_key => $_opt_attr_val) {
$data_content .= $_opt_attr_key . '=' . '"' . $_opt_attr_val . '"';
}
if ($data_content != '') {
$data_content = ' ' . $data_content;
}
}
$select .= '<option value="' . $key . '"' . $_selected . $data_content . $data_sub_text . '>' . $val . '</option>';
}
$select .= '</select>';
$select .= '</div>';
return $select;
}
get sellers arrays in db functions
function get_sellers()
{
$CI = & get_instance();
return $CI->db->get(db_prefix() . 'sellers')->result_array();
}
I have created a column "sellers" in my table but it sends numbers and not text.
I need it so that when the form is saved it will submit the title and display it in the selection.
Thanks you
View form:
click

Add specific attribute and values to input and label html tags in Woocommerce

I'm trying to add style, depending on whether the checkbox is clicked. This code is missing "id" and "for" for input and label (line 11). Logical decision to add generation of numbers. How to do it correctly?
foreach ($choices as $choice) {
$attr = '';
$key_val = explode("|", $choice);
/* It has to be two items ( Value => Label ), otherwise don't proceed */
if (count($key_val) == 2) {
if (in_array(trim($key_val[0]), $defaults)) {
$attr = 'checked';
}
/* For admin field, we don't need <li></li> wrapper */
$html .= (($_ptype != "wccaf") ? '<li>' : '') . '<input type="checkbox" data-has_field_rules="'.$has_field_rules.'" data-is_pricing_rules="'.$_is_pricing_rules.'" class="' . $_ptype . '-field ' . $_class . '" name="' . esc_attr($_meta["name"] . $_index) . '[]" value="' . esc_attr(trim($key_val[0])) . '" ' . $attr . ' ' . $_ptype . '-type="checkbox" ' . $_ptype . '-pattern="mandatory" ' . $_ptype . '-mandatory="' . $_meta["required"] . '" ' . $_readonly . ' /><label class="wcff-option-wrapper-label">' . esc_attr(trim($key_val[1])) . '</label>' . (($_ptype != "wccaf") ? '</li>' : '');
}
}
Updated
Try the following (untested), that will add a for attribute + value to the <label> and an id attribute + value to the <input>:
foreach ($choices as $choice) {
$attr = '';
$key_val = explode("|", $choice);
/* It has to be two items ( Value => Label ), otherwise don't proceed */
if (count($key_val) == 2) {
if (in_array(trim($key_val[0]), $defaults)) {
$attr = 'checked';
}
$sprintf = sprintf( '<input type="checkbox" %s %s %s %s %s %s %s /><label %s class="wcff-option-wrapper-label">%s</label>',
'id="' . esc_attr($_meta["name"] . $_index) . '"',
'data-has_field_rules="'.$has_field_rules.'"',
'data-is_pricing_rules="'.$_is_pricing_rules.'"',
'class="' . $_ptype . '-field ' . $_class . '"',
'name="' . esc_attr($_meta["name"] . $_index) . '[]"',
'value="' . esc_attr(trim($key_val[0])) . '"',
$attr . ' ' . $_ptype . '-type="checkbox" ' . $_ptype . '-pattern="mandatory' . $_meta["required"] . '" ' . $_readonly,
'for="' . esc_attr($_meta["name"] . $_index) . '"',
esc_attr(trim($key_val[1]) ) );
$html .= $_ptype != "wccaf" ? '<li>'.$sprintf.'</li>' : $sprintf;
}
}
I have embedded the code in a sprintf() function to make it more readable, functional and easy to tune.

SP Page Builder php errors ( Undefined variable, Undefined property)

i installed a Joomla template and some errors are appearing in homepage, the Errors are related to the Sp Page Builder component.
How can i fix these errors?
Here's a document with the erros - https://drive.google.com/open?id=0B1toGflgmV7fZi1SQ051QWZxZFE
And the site.php
<?php
/**
* Flex 1.0 #package SP Page Builder
* Template Name - Flex
* #author Aplikko http://www.aplikko.com
* #copyright Copyright (c) 2015 Aplikko
* #license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
// no direct access
defined('_JEXEC') or die;
JLoader::register('JHtmlString', JPATH_LIBRARIES.'/joomla/html/html/string.php');
AddonParser::addAddon('sp_latest_posts','sp_latest_posts_addon');
function get_categories($parent=1) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select('*')
->from($db->quoteName('#__categories'))
->where($db->quoteName('extension') . ' = ' . $db->quote('com_content'))
->where($db->quoteName('published') . ' = ' . $db->quote(1))
->where($db->quoteName('parent_id') . ' = ' . $db->quote($parent))
->order($db->quoteName('created_time') . ' DESC');
$db->setQuery($query);
$cats = $db->loadObjectList();
$categories = array($parent);
foreach ($cats as $key => $cat) {
$categories[] = $cat->id;
}
return $categories;
}
function sp_latest_posts_addon($atts){
extract(spAddonAtts(array(
"title" => '',
"heading_selector" => 'h3',
"title_fontsize" => '',
"title_text_color" => '',
"title_margin_top" => '',
"title_margin_bottom" => '',
"show_image" => '',
"show_date" => '',
"show_category" => '',
"show_intro_text" => '',
"show_author" => '',
"item_limit" => '',
"intro_text_limit" => '100',
"column_no" => '3',
"image_alignment" => '',
"category" => '',
"style" => '',
"class" => '',
), $atts));
$app = JFactory::getApplication();
$doc = JFactory::getDocument();
// Database Query
require_once JPATH_SITE . '/components/com_content/helpers/route.php';
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select('a.*')
->from($db->quoteName('#__content', 'a'))
->select($db->quoteName('b.alias', 'category_alias'))
->select($db->quoteName('b.title', 'category'))
->join('LEFT', $db->quoteName('#__categories', 'b') . ' ON (' . $db->quoteName('a.catid') . ' = ' . $db->quoteName('b.id') . ')')
->where($db->quoteName('b.extension') . ' = ' . $db->quote('com_content'))
->where($db->quoteName('a.state') . ' = ' . $db->quote(1))
->where($db->quoteName('a.catid')." IN (" . implode( ',', get_categories($category) ) . ")")
->where($db->quoteName('a.access')." IN (" . implode( ',', $authorised ) . ")")
->order($db->quoteName('a.created') . ' DESC')
->setLimit($item_limit);
$db->setQuery($query);
$items = $db->loadObjectList();
// End Database Query
$style == 'flex' ? $flex_style = ' flex' : '';
$style == 'blog' ? $blog_style = ' blog' : '';
$blog_style = $output = '<div class="sppb-addon sppb-addon-latest-posts'.$flex_style.$blog_style.' sppb-row ' . $class . '">';
if ($title) {
$output .= '<div class="sppb-section-title">';
$output .= '<'.$heading_selector.' class="sppb-addon-title" style="' . $title_style . '"> ' . $title . '</' . $heading_selector . '>';
$output .= '</div>'; // END :: title
}
$output .= '<div class="sppb-addon-content">';
$output .= '<div class="latest-posts clearfix">';
foreach(array_chunk($items, $column_no) as $items) {
$output .= '<div>';
foreach ($items as $item) {
$item->slug = $item->id . ':' . $item->alias;
$item->catslug = $item->catid . ':' . $item->category_alias;
$item->user = JFactory::getUser($item->created_by)->name;
if ($access || in_array($item->access, $authorised)) {
// We know that user has the privilege to view the article
$item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catid, $item->language));
$item->catlink = JRoute::_(ContentHelperRoute::getCategoryRoute($item->catslug, $item->catid, $item->language));
} else {
$item->link = JRoute::_('index.php?option=com_users&view=login');
$item->catlink = JRoute::_('index.php?option=com_users&view=login');
}
$tplParams = JFactory::getApplication()->getTemplate(true)->params;
$params = $item->params;
$attribs = json_decode($item->attribs);
$images = json_decode($item->images);
$imgsize = $tplParams->get('blog_list_image', 'default');
$intro_image = '';
if(isset($attribs->spfeatured_image) && $attribs->spfeatured_image != '') {
if($imgsize == 'default') {
$intro_image = $attribs->spfeatured_image;
} else {
$intro_image = $attribs->spfeatured_image;
$basename = basename($intro_image);
$list_image = JPATH_ROOT . '/' . dirname($intro_image) . '/' . JFile::stripExt($basename) . '_'. $imgsize .'.' . JFile::getExt($basename);
if(file_exists($list_image)) {
$intro_image = JURI::root(true) . '/' . dirname($intro_image) . '/' . JFile::stripExt($basename) . '_'. $imgsize .'.' . JFile::getExt($basename);
}
}
} elseif(isset($images->image_intro) && !empty($images->image_intro)) {
$intro_image = $images->image_intro;
}
if($column_no == '1') {
if ($show_image) {
$image_alignment == 'left' ? $img_column = 'sppb-col-sm-4 column-1 pull-left match-height' : $img_column = 'sppb-col-sm-4 column-1 pull-right match-height';
}
if ($show_image) {
$image_alignment == 'right' ? $content_column = 'sppb-col-sm-8 column-1 pull-left match-height' : $content_column = 'sppb-col-sm-8 column-1 pull-right match-height';
} else {
$image_alignment == 'right' ? $content_column = 'sppb-col-sm-12 column-1' : $content_column = 'sppb-col-sm-12 column-1';
}
$h2style = ' style="font-size:180%;line-height:1.4;"';
$img_wrapper_margin = ' style="margin:0;"';
if ($image_alignment == 'left') {
$inner_padding = ' style="padding:0 0 0 30px;"';
} else {
$inner_padding = ' style="padding:0 30px 0 0;"';
}
}
// match-height
$column_no > '1' ? $match_height = ' match-height' : '';
// Flex Style
if($style == 'flex') {
$output .= '<div class="latest-post sppb-col-sm-' . round(12/$column_no) . ' columns-'.$column_no.'">';
$output .= '<div class="latest-post-item">';
if($column_no == '1') {
$output .= '<div class="row-fluid">';
}
if(!empty($intro_image) || (isset($images->image_intro) && !empty($images->image_intro))) {
if ($show_image) {
if($column_no == '1') {
$output .= '<div style="padding:0" class="'.$img_column.'">';
}
$output .= '<div class="img-wrapper">';
$output .= '<img class="post-img" src="' . $intro_image . '" alt="' . $item->title . '" /><div class="caption-content">' . $item->title . '<em class="caption-category"><span class="posted-in">'. JText::_('COM_SPPAGEBUILDER_ADDON_POSTED_IN') .'</span>'. $item->category . '</em></div>';
$output .= '</div>';
if($column_no == '1') {
$output .= '</div>';
}
}
}
if($column_no == '1') {
$output .= '<div'.$inner_padding.' class="'.$content_column.'">';
}
$output .= '<div class="latest-post-inner match-height">';
if (($show_date || $show_intro_text || $show_author) != 1) {
$output .= '<h2 style="margin:0" class="entry-title">' . $item->title . '</h2>';
} else {
$output .= '<h2'.$h2style.' class="entry-title">' . $item->title . '</h2>';
}
if ($show_date) {
$output .= '<div class="entry-meta"><span class="entry-date">' . JHtml::_('date', $item->created, 'DATE_FORMAT_LC1') . '</span></div>';
}
if ($show_intro_text) {
$output .= '<p class="intro-text" >' . JHtml::_('string.truncate', strip_tags($item->introtext), $intro_text_limit) . '</p>';
}
$show_author || $show_category ? $output .= '<hr />' : '';
if ($show_author) {
$output .= '<span class="post-author"><span class="entry-author">' . JText::_('COM_SPPAGEBUILDER_ADDON_POSTED_BY'). '</span> ' . $item->user . '</span>';
}
if ($show_category) {
$show_author ? $posted_in_category = ' cat-inline' : '';
$output .= '<span class="category'.$posted_in_category.'"><span class="posted-in">'. JText::_('COM_SPPAGEBUILDER_ADDON_CATEGORY') .'</span>'. $item->category . '</span>';
}
if($column_no == '1') {
$output .= '</div>';
$output .= '</div>';
}
$output .= '</div>';
if($column_no == '1') {
$output .= '<div class="post-divider"></div>';
}
$output .= '</div>';
// Default & Blog styles
} else {
$output .= '<div class="latest-post sppb-col-sm-' . round(12/$column_no) . ' columns-'.$column_no.'">';
$output .= '<div class="latest-post-inner' . $match_height . '">';
if($column_no == '1') {
$output .= '<div class="row-fluid">';
}
if ($show_image) {
if($column_no == '1') {
$output .= '<div class="'.$img_column.'">';
}
$output .= '<div'.$img_wrapper_margin.' class="img-wrapper">';
$output .= '<img class="post-img" src="' . $intro_image . '" alt="' . $item->title . '" />';
$output .= '</div>';
if($column_no == '1') {
$output .= '</div>';
}
}
if($column_no == '1') {
$output .= '<div class="'.$content_column.'">';
}
if ($show_date) {
$output .= '<div class="entry-meta"><span class="entry-date"> ' . JHtml::_('date', $item->created, 'DATE_FORMAT_LC1') . '</span></div>';
}
$output .= '<h2'.$h2style.' class="entry-title">' . $item->title . '</h2>';
if ($show_intro_text) {
$output .= '<p class="intro-text" >' . JHtml::_('string.truncate', strip_tags($item->introtext), $intro_text_limit) . '</p>';
}
$show_author || $show_category ? $output .= '<hr />' : '';
if ($show_author) {
$output .= '<span class="post-author"><span class="entry-author">' . JText::_('COM_SPPAGEBUILDER_ADDON_POSTED_BY'). ' ' . $item->user . '</span></span>';
}
if ($show_category) {
$show_author ? $posted_in_category = ' cat-inline' : '';
$output .= '<span class="category'.$posted_in_category.'"><span class="posted-in">'. JText::_('COM_SPPAGEBUILDER_ADDON_CATEGORY') .'</span>'. $item->category . '</span>';
}
if($column_no == '1') {
$output .= '</div>';
$output .= '</div>';
}
$output .= '</div>';
}
$output .= '</div>';
}
$output .= '</div>';
}
$output .= '</div>';
$output .= '</div>';
$output .= '</div>';
$column_no == '1' ? $column_no_1 = '.column-1 {margin:10px auto;padding:0!important;}' : '';
// Add styles #media rulepost-img
if($style == 'flex') {
$custom_style = ''
. '#media screen and (max-width: 768px) {'
. $column_no_1
. '.img-wrapper a {font-size:150%;line-height:1.5;}'
. '}';
$doc->addStyleDeclaration($custom_style);
}
if ($column_no>='3') {
$custom_style_3 = ''
. '#media screen and (min-width: 992px) and (max-width: 1199px){'
. '.columns-'.$column_no.'{width:33.3333%;}'
. '}'
. '#media screen and (min-width: 768px) and (max-width: 991px){'
. '.columns-'.$column_no.'{width:50%}'
. '}';
$doc->addStyleDeclaration($custom_style_3);
}
if($column_no=='5') {
$custom_style_5 = ''
. '.columns-'.$column_no.' {width:20%}'
. '#media screen and (min-width: 992px) and (max-width: 1199px){'
. '.columns-'.$column_no.'{width:33.3333%;}'
. '}'
. '#media screen and (min-width: 768px) and (max-width: 991px){'
. '.columns-'.$column_no.'{width:50%}'
. '}'
. '#media screen and (max-width: 767px){'
. '.columns-'.$column_no.'{width:100%}'
. '}';
$doc->addStyleDeclaration($custom_style_5);
}
return $output;
}
Thanks!
There is many errors, but all of them are variable that have not been declared before using it, as example :
$style == 'flex' ? $flex_style = ' flex' : '';
$style == 'blog' ? $blog_style = ' blog' : '';
$blog_style = $output = '<div class="sppb-addon sppb-addon-latest-posts'.$flex_style.$blog_style.' sppb-row ' . $class . '">';
In this case $flex_style and $blog_style are not declared, you should write this instead :
$flex_style = style == 'flex' ? ' flex' : '';
$blog_style = $style == 'blog' ? ' blog' : '';
That is just an example, but if you search a little you'll find other issue like this one.

php codeIgniter how to return null when the array is empty?

I am checking some conditional statements and finally outputting a value. I get the correct output. But when the $query is empty i want to return null. Otherwise it shows a php error. I want to get rid from the php error when the query is empty. I have no idea about this. If anyone has an idea it would be a great help.
here is my model method.
function get_calendar_data($year, $month) {
$query = $this->db->select('date_cal,title,type,description,telephone_number,advanced_payment_status')->from('reservations')->like('date_cal', "$year-$month", 'after')->order_by('date_cal', "asc")->get();
if ($query!='') {
$content = "";
$lastDay = -1;
$index = 0;
foreach ($query->result() as $row) {
if ($lastDay != intval(substr($row->date_cal, 8, 2))) {
if ($index > 0) {
if ($content != '') {
$cal_data[$lastDay] = $content;
$content = '';
}
}
$index = 0;
}
if ($row->title == 'RP' && $row->type == 'AM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="rp_am_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'RP' && $row->type == 'AM' && $row->advanced_payment_status=='no') {
$content .= '<div class="rp_am_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'RP' && $row->type == 'PM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="rp_pm_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'RP' && $row->type == 'PM' && $row->advanced_payment_status=='no') {
$content .= '<div class="rp_pm_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'GK' && $row->type == 'AM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="gk_am_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'GK' && $row->type == 'AM' && $row->advanced_payment_status=='no') {
$content .= '<div class="gk_am_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'GK' && $row->type == 'PM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="gk_pm_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
}else if ($row->title == 'GK' && $row->type == 'PM' && $row->advanced_payment_status=='no') {
$content .= '<div class="gk_pm_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
}else{
$content .='<div class="add"></div>';
}
$lastDay = intval(substr($row->date_cal, 8, 2));
$index++;
}
if ($lastDay != -1 && $content != '') {
$cal_data[$lastDay] = $content;
}
return $cal_data;
} else if($query==''){
return Null;
}
}
I am getting this php error when the $query is empty. It says about the return value which outputting when the $query is not empty.
Define $cal_data = NULL; at the top of the function. If the condition doesnot satisfied then $cal_data will never be defined.
If it is define as NULL then if the condition is satisfied it will return the proper data else NULL.
$cal_data = NULL;
... rest of the code ...
if ($lastDay != -1 && $content != '') {
$cal_data[$lastDay] = $content;
}
return $cal_data;
Make sure that you always write the DB related code in try..catch blocks. Assuming that the $db->select returns array, you can write the following:
try{
if(isset($query) && empty($query)){
return null;
}
<Code line 1>
<Code line 2>
<Code line 3>
...
}catch(Exception $e){
return null; //or what ever you want to return.
}
One more thing to remember your first try did not work since the query is never returned empty. If i write a query that returns zero rows from the database the $query will be like
CI_DB_mysql_result Object
(
[conn_id] => Resource id #40
[result_id] => Resource id #45
[result_array] => Array
(
)
[result_object] => Array
(
)
[custom_result_object] => Array
(
)
[current_row] => 0
[num_rows] => 0
[row_data] =>
)
The proper way for checking wether the array is empty is by calling the
result()
method for your query.
that is
$query->result();
will return an empty array for zero rows returned.
Or else you can try to check wether the
$query[num_rows]>0
Hope it helped.
User num_rows() functions to get number of rows in query.
function get_calendar_data($year, $month) {
$query = $this->db->select('date_cal,title,type,description,telephone_number,advanced_payment_status')->from('reservations')->like('date_cal', "$year-$month", 'after')->order_by('date_cal', "asc")->get();
$row_num=$query->num_rows();
if ($row_num>0) {
$content = "";
$lastDay = -1;
$index = 0;
foreach ($query->result() as $row) {
if ($lastDay != intval(substr($row->date_cal, 8, 2))) {
if ($index > 0) {
if ($content != '') {
$cal_data[$lastDay] = $content;
$content = '';
}
}
$index = 0;
}
if ($row->title == 'RP' && $row->type == 'AM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="rp_am_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'RP' && $row->type == 'AM' && $row->advanced_payment_status=='no') {
$content .= '<div class="rp_am_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'RP' && $row->type == 'PM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="rp_pm_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'RP' && $row->type == 'PM' && $row->advanced_payment_status=='no') {
$content .= '<div class="rp_pm_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'GK' && $row->type == 'AM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="gk_am_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'GK' && $row->type == 'AM' && $row->advanced_payment_status=='no') {
$content .= '<div class="gk_am_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'GK' && $row->type == 'PM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="gk_pm_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
}else if ($row->title == 'GK' && $row->type == 'PM' && $row->advanced_payment_status=='no') {
$content .= '<div class="gk_pm_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
}else{
$content .='<div class="add"></div>';
}
$lastDay = intval(substr($row->date_cal, 8, 2));
$index++;
}
if ($lastDay != -1 && $content != '') {
$cal_data[$lastDay] = $content;
}
return $cal_data;
} else {
return Null;
}
}

Categories