How to retrieve the array values from multiples checkbox? I have problem when I retrieve value array and echo the value. I get this error
Severity: Warning
Message: in_array() expects parameter 2 to be array, string given
Filename: page/update.php.
Please, could you help me again? Thank you.
You find three files: View, Model and Controller. Please check where I wrong...
UPDATE.PHP:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<div class="row">
<div class="col-sm-12">
<?php echo form_open('page_controller/update_page_post'); ?>
<div class="form-group">
<div class="row">
<div class="col-sm-3 col-xs-12">
<label><?php echo trans('subcategory'); ?></label>
</div>
</div><div class="col-xm-12">
<div class="table-responsive">
<table class="table table-bordered table-striped" role="grid">
<tbody>
<tr>
<?php $valuesub = ($page->subcat_recip_id); ?>
<?php $array_of_values = explode(",", $valuesub);
//if ($item['parent_id'] != "0" && $item['subcat_recip_id'] == "0") :
foreach ($array_of_values as $item) {
if(in_array($valuesub,$item)): { ?>
<td>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" CHECKED> <?php echo html_escape($item["title"]);
} ?>
<?php else: { ?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>"> <?php echo html_escape($item["title"]);
}
endif; }?>
</td>
<?php echo html_escape($valuesub); ?></tr>
</tbody>
</table>
</div>
</div>
</div>
PAGE_CONTROLLER.PHP
public function update_page_post()
{
//validate inputs
$this->form_validation->set_rules('title', trans("title"), 'required|xss_clean|max_length[500]');
if ($this->form_validation->run() === false) {
$this->session->set_flashdata('errors', validation_errors());
$this->session->set_flashdata('form_data', $this->page_model->input_values());
redirect($this->agent->referrer());
} else {
//get id
$id = $this->input->post('id', true);
$redirect_url = $this->input->post('redirect_url', true);
if (!$this->page_model->check_page_name()) {
$this->session->set_flashdata('form_data', $this->page_model->input_values());
$this->session->set_flashdata('error', trans("msg_page_slug_error"));
redirect($this->agent->referrer());
exit();
}
if ($this->page_model->update($id)) {
$this->session->set_flashdata('success', trans("msg_updated"));
if (!empty($redirect_url)) {
redirect($redirect_url);
} else {
redirect(admin_url() . 'pages');
}
} else {
$this->session->set_flashdata('form_data', $this->page_model->input_values());
$this->session->set_flashdata('error', trans("msg_error"));
redirect($this->agent->referrer());
}
}
}
PAGE_MODEL.PHP
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Page_model extends CI_Model
{
//input values
public function input_values()
{
$checkbox = implode(',', $this->checkBox());
$data = array(
'lang_id' => $this->input->post('lang_id', true),
'title' => $this->input->post('title', true),
'slug' => $this->input->post('slug', true),
'page_description' => $this->input->post('page_description', true),
'page_keywords' => $this->input->post('page_keywords', true),
'page_content' => $this->input->post('page_content', false),
'page_order' => $this->input->post('page_order', true),
'parent_id' => $this->input->post('parent_id', true),
'page_active' => $this->input->post('page_active', true),
'title_active' => $this->input->post('title_active', true),
'breadcrumb_active' => $this->input->post('breadcrumb_active', true),
'right_column_active' => $this->input->post('right_column_active', true),
'need_auth' => $this->input->post('need_auth', true),
'howmany_people' => $this->input->post('howmany_people', true),
'difficulty' => $this->input->post('difficulty', true),
'howmany_time' => $this->input->post('howmany_time', true),
'location' => $this->input->post('location', true),
'subcat_recip_id' => $checkbox
);
return $data;
}
public function checkBox(){
$count = count($_POST['subcat_recip_id']);
for($n=0; $n<$count; $n++){
$checkbox[$n] = $_POST['subcat_recip_id'][$n];
}
return $checkbox;
}
//update page
public function update($id)
{
//set values
$data = $this->page_model->input_values();
if (empty($data["slug"])) {
//slug for title
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
in your you view,
<tr>
<?php $valuesub = ($page->subcat_recip_id); ?>
<?php $array_of_values = explode(",", $valuesub);
foreach ($array_of_values as $item) {
if(in_array($subcat_recip_id,$item)): { ?>
<td>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" CHECKED> <?php echo html_escape($item["title"]);
} ?>
<?php else: { ?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>"> <?php echo html_escape($item["title"]);
}
endif; }?>
</td>
<?php echo html_escape($valuesub); ?>
</tr>
change to :
<tr>
<?php $valuesub = ($page->subcat_recip_id);
$array_of_values = explode(",", $valuesub); ?>
<td>
<?php foreach ($array_of_values as $item) :?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" <?=(in_array($subcat_recip_id,$item))?"CHECKED":""?>> <?=html_escape($item["title"]);?>'
<?php endforeach; ?>
</td>
<?=html_escape($valuesub)?>
</tr>
in model :
public function update($id){
//set values
$data = $this->page_model->input_values();
if (empty($data["slug"])) {
//slug for title
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
change to :
public function update($id){
$data = $this->input_values();
if (empty($data["slug"])) {
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
please update if you getting error,
tq
Well, it remains a bug but with some changes yr last code works. The great problem is the loop, it re-load the $valuesub for how many times is the value. Ie. If the array is composed of three values, it reads three times the same value. Pls see the two screenshots: https://www.screencast.com/t/MfiEDhdFuX
I can't get this loop off !!
Code
<td>
<?php foreach ($menu_links as $item) :
$valuesub = ($page->subcat_recip_id);
$array_of_values = explode("," , $valuesub);
if ($item['parent_id'] != "0" && $item['subcat_recip_id'] == "0") :
foreach($array_of_values as $dt): ?>
<?php //if(in_array($dt,$item)): ?>
<input type="checkbox" name="subcat_recip_id" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" <?=(in_array($dt,$item))?"CHECKED":""?>> <?=html_escape($item["title"]);?>
<?php endforeach; endif;?>
<?php endforeach; ?>
</td><?php echo html_escape($valuesub); ?>
what should i do to fix this error ?
ERR (3): Warning: Invalid argument supplied for foreach() in /app/design/adminhtml/default/default/template/canonical/canonical/edit/tab/header.phtml on line 79
<?php if ( Mage::getSingleton('admin/session')->isAllowed('admin/global_search') ): ?>
<fieldset>
<legend>Search</legend>
<span id="global_search_indicator" class="autocomplete-indicator" style="display: none">
<img src="<?php echo $this->getSkinUrl('images/ajax-loader.gif') ?>" alt="<?php echo $this->__('Loading...') ?>" class="v-middle"/>
</span>
<?php $defSearch = $this->__('Global Record Search') ?>
<input id="global_search" name="query" type="text" class="input-text" value="<?php if(!empty($query)): ?><?php echo $query ?><?php else: ?><?php echo $defSearch ?><?php endif ?>" onfocus="if(this.value=='<?php echo $defSearch ?>')this.value=''; " onblur="if(this.value=='')this.value='<?php echo $defSearch ?>';" />
<div id="global_search_autocomplete" class="autocomplete"></div>
<script type="text/javascript">
new Ajax.Autocompleter(
'global_search',
'global_search_autocomplete',
'<?php echo $this->getUrl('adminhtml/index/globalSearch') ?>',
{
paramName:"query",
minChars:2,
indicator:"global_search_indicator",
updateElement:getSelectionId,
evalJSON:'force'
}
);
function getSelectionId(li) {
location.href = li.getAttribute('url');
}
</script>
</fieldset>
<?php endif; ?>
</div>
</div>
<?php if(Mage::getStoreConfig('advanced/modules_disable_output/FME_Canonical')==0) : ?>
<?php
$product_id = Mage::app()->getRequest()->getParam('id');
$_product = Mage::getModel('catalog/product')->load($product_id);
$selected = $_product->getData('fme_canonicalurl');
$catIds = $_product->getCategoryIds();
foreach ($catIds as $key )
{
$catCollection = Mage::getResourceModel('catalog/category_collection')
->addAttributeToFilter('entity_id', $key);
foreach($catCollection as $cat)
{
$dat[] = $cat->getId();
}
}
?>
<script type="text/javascript">
window.onload = function () {
if(categories = document.getElementById("fme_canonicalurl"))
{
var categories = document.getElementById("fme_canonicalurl");
var newOption = document.createElement('option');
newOption.text = "<?php echo $_product->getUrlPath() ?>";
newOption.setAttribute('value', "<?php echo $_product->getUrlPath() ?>");
categories.appendChild(newOption);
<?php
foreach ($dat as $value ) {
echo "var newOption = document.createElement('option');";
$_category = Mage::getModel('catalog/category')->load($value);
$url = $_product->getUrlPath($_category); ?>
newOption.text = "<?php echo $url ?>" ;
newOption.setAttribute('value', '<?php echo $url ?>');
categories.appendChild(newOption);
<?php
}
?>
function setSelectedIndex(s, v) {
for ( var i = 0; i < s.options.length; i++ ) {
if ( s.options[i].value == v ) {
s.selectedIndex = i;
return;
}
}
}
setSelectedIndex(categories,"<?php echo $selected?>");
}
}
Your problem is that you're pushing data into the $dat array from within a loop, but you didn't initialize it first. In the case where no results are looped and no data is pushed to $dat, it is then undefined when you try and loop over $dat later on.
Initialize it first:
$catIds = $_product->getCategoryIds();
$dat = array();
foreach ($catIds as $key) {
$catCollection = Mage::getResourceModel('catalog/category_collection')
->addAttributeToFilter('entity_id', $key);
foreach ($catCollection as $cat) {
$dat[] = $cat->getId();
}
}
I have a following code that shows category by level, but I have to show all the sub categories from that specific category.
<?php
$_cat = new Mage_Catalog_Block_Navigation();
$currentCat = $_cat->getCurrentCategory();
$subCats = Mage::getModel('catalog/category')->load($currentCat->getId())- >getChildren();
$subCatIds = explode(',',$subCats);
?>
<?php ////////////////////////level-3///////////////////////////// ?>
<?php $category = Mage::registry('current_category');
$category->getParentCategories();
if ( $category->getLevel() == 3 ) : ?>
<div class="cat_drop_ser_wrap">
<?php $currentCat = Mage::getModel('catalog/category')->load($currentCat- >getId()) ?>
<select class="select_class" onchange="window.location.href=this.value">
<option value="#">-Select</option>
<?php foreach($subCatIds as $subCatId): ?>
<?php $subCat = Mage::getModel('catalog/category')->load($subCatId); ?>
<?php if($subCat->getIsActive()): ?>
<option value="<?php echo $subCat->getUrl() ?>">
<?php echo $subCat->getName(); ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<?php endif; ?><!--if--level-3-->
Thanks in advance.
Ok in case anyone needs it following will show the sub categories and so on:
<?php //////sub////// ?>
<?php
$category_levels = Mage::getModel('catalog/category')->load($category->getId());
$subcategories = $category_levels->getChildrenCategories();
if (count($subcategories) > 0){
foreach($subcategories as $subcategory){
$category_levels_two = Mage::getModel('catalog/category')->load($subcategory->getId());
$subcategoriess = $category_levels_two->getChildrenCategories();
if (count($subcategoriess) > 0){
$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_category', 'category_dropdown_label');
$text = $category_levels_two->getCategoryDropdownLabel();
echo '<div class="empty_serch_select_1 cat_drop_ser_wrap 2">';
echo '<label>' . $text . '</label>';
echo '<select disabled="disabled">';
echo '<option value="#">-Select</option>';
echo '<select>';
echo '</div>';
break;
}
}
}
?>
<?php //////sub-sub////// ?>
<?php
$category_levels = Mage::getModel('catalog/category')->load($category->getId());
$subcategories = $category_levels->getChildrenCategories();
echo '<div class="empty_serch_select_2 cat_drop_ser_wrap 3">';
if (count($subcategories) > 0){
foreach($subcategories as $subcategory){
$category_levels_two = Mage::getModel('catalog/category')->load($subcategory->getId());
$subcategoriess = $category_levels_two->getChildrenCategories();
if (count($subcategoriess) > 0){
foreach($subcategoriess as $subcategorys){
$category_levels_three = Mage::getModel('catalog/category')->load($subcategorys->getId());
$subcategoriesss = $category_levels_three->getChildrenCategories();
if (count($subcategoriesss) > 0){
$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_category', 'category_dropdown_label');
$text = $category_levels_three->getCategoryDropdownLabel();
echo '<label>' . $text . '</label>';
break;
}
}
}
}
}
echo '<select disabled="disabled">';
echo '<option value="#">-Select</option>';
echo '<select>';
echo '</div>';
?>
<?php //////sub-sub-sub////// ?>
<?php
$category_levels = Mage::getModel('catalog/category')->load($category->getId());
$subcategories = $category_levels->getChildrenCategories();
echo '<div class="empty_serch_select_2 cat_drop_ser_wrap 3">';
if (count($subcategories) > 0){
foreach($subcategories as $subcategory){
$category_levels_two = Mage::getModel('catalog/category')->load($subcategory->getId());
$subcategoriess = $category_levels_two->getChildrenCategories();
if (count($subcategoriess) > 0){
foreach($subcategoriess as $subcategorys){
$category_levels_three = Mage::getModel('catalog/category')->load($subcategorys->getId());
$subcategoriesss = $category_levels_three->getChildrenCategories();
if (count($subcategoriesss) > 0){
foreach($subcategoriesss as $subcategorys){
$category_levels_three = Mage::getModel('catalog/category')->load($subcategorys->getId());
$subcategoriessss = $category_levels_three->getChildrenCategories();
if (count($subcategoriessss) > 0){
$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_category', 'category_dropdown_label');
$text = $category_levels_three->getCategoryDropdownLabel();
echo '<label>' . $text . '</label>';
break;
}
}
}
}
}
}
}
echo '<select disabled="disabled">';
echo '<option value="#">-Select</option>';
echo '<select>';
echo '</div>';
?>
I'm not that good at php. What i have is a list of items looped with endforeach. What I want is that the first loop will have a class of col-lg-12 and from the second one that class will become col-lg-6. How can I achive that?
Here's the code:
<?php $firstLoop = true;
foreach( $network_value as $key => $value ){
if( $firstLoop ){
echo '<div class="col-lg-12">';
}
echo '<div class="col-lg-6">';
$firstLoop = false;
} ?>
^This is the code that I've tried, but it's not working how i wanted.
<?php if ($img): ?>
<img src="<?php echo $thumb->src ?>" width="<?php echo $thumb->width ?>" height="<?php echo $thumb->height ?>" alt="" />
<?php endif; ?>
<h4>
<div class="circle"><?php echo $datePublic = date('d M', strtotime($page->getCollectionDatePublic())); ?></div>
<br>
<a class="blogTitle" href="<?php echo $url ?>" target="<?php echo $target ?>"><?php echo $title ?></a></h4>
<h6>Posted by <?php echo $author; ?></h6>
<br>
<p><?php echo $description ?></p>
</div>
<?php endforeach; ?>
The most simple way to do it is to add a counter and check if it is the first value in the counter.
<?php
$counter = 0;
foreach( $network_value as $key => $value )
{
if($counter == 0){
echo '<div class="col-lg-12">';
} else {
echo '<div class="col-lg-6">';
}
$counter++;
}
?>
Also I want to add that there are two ways of using foreach and if-statements, but you are trying to mix them, which is wrong.
The first method is using brackets "{" and "}":
foreach($users as $user) {
// do things for each user
echo $user->name; // Example of writing out users name
}
And if-statement:
if(true) {
// do something
}
The second method is using "foreach(statement):" and "endforeach;"
foreach($users as $user):
// do things for each user
echo $user->name; // Example of writing out users name
endforeach;
And if-statement:
if(true):
// do something
endif;
Edited:
In your case you can use:
<?php
foreach ($pages as $key=>$page):
if($key==0){
echo '<div class="col-lg-12">';
} if($key==1){
echo '<div class="col-lg-6">';
}
endforeach; ?>
Or you can use:
<?php
foreach ($pages as $key=>$page):
if($key==0){
echo '<div class="col-lg-12">';
} else {
echo '<div class="col-lg-6">';
}
endforeach; ?>
OLD:
foreach($array as $key=>$row){
if($key==0){
echo '<div class="col-lg-12"></div>';
}
if($key==5){
echo '<div class="col-lg-6"></div>';
}
// OR try use %
if($key%2 == 0){
echo '<div class="col-lg-12"></div>';
} else {
echo '<div class="col-lg-12"></div>';
}
I use this code to check which tags are used within a Wordpress category. It renders a checkbox list. I want the form to remember my choice after submit.
This is my code:
<form name="tags" onChange="document.forms.tags.submit();">
<?php
if (is_category()){
$cat = get_query_var('cat');
$yourcat = get_category ($cat);
}
$tag_IDs = array();
query_posts('category_name='.$yourcat->slug);
if (have_posts()) : while (have_posts()) : the_post();
$posttags = get_the_tags();
if ($posttags):
foreach($posttags as $tag) {
if (!in_array($tag->term_id , $tag_IDs)):
$tag_IDs[] = $tag->term_id;
$tag_names[$tag->term_id] = $tag->name;
$tag_slug[$tag->term_id] = $tag->slug;
endif;
}
endif;
endwhile; endif;
wp_reset_query();
if (!empty($tag_IDs)){
echo '<h3>Het meest geschikt voor</h3>';
echo "<input type=\"radio\" name=\"tag\" value=\"\"> Alles weergeven<br>";
}
foreach($tag_IDs as $tag_ID){
echo '<input type="radio" name="tag" value="'.$tag_slug[$tag_ID].'"> '.$tag_names[$tag_ID].'<br>';
}
?>
</form>
Before I was using this code to remember the choice, but it doesn't work with the above code anymore:
if((isset($_GET["tag"])) && $_GET["tag"] == "tag-example") { echo "checked";}
I thought it would work like this, but it doesn't:
echo '<input type="radio" name="tag" value="'.$tag_slug[$tag_ID].'" '.if((isset($_GET["tag"])) && $_GET["tag"] == "oudere-kinderen") { echo "checked";}.'> '.$tag_names[$tag_ID].'<br>';
How can I get the form to remember the checkbox choice?
Solution:
With help from #Jouke I came to this solution:
if (is_category()){
$cat = get_query_var('cat');
$yourcat = get_category ($cat);
}
$tag_IDs = array();
query_posts('category_name='.$yourcat->slug);
if (have_posts()) : while (have_posts()) : the_post();
$posttags = get_the_tags();
if ($posttags):
foreach($posttags as $tag) {
if (!in_array($tag->term_id , $tag_IDs)):
$tag_IDs[] = $tag->term_id;
$tag_names[$tag->term_id] = $tag->name;
$tag_slug[$tag->term_id] = $tag->slug;
endif;
}
endif;
endwhile; endif;
wp_reset_query();
if (!empty($tag_IDs)){
echo '<h3>Het meest geschikt voor</h3>';
echo "<input type=\"radio\" name=\"tag\" value=\"\"> Alles weergeven<br>";
}
foreach($tag_IDs as $tag_ID){
$test = $tag_slug[$tag_ID];
echo '<input type="radio" name="tag" value="'.$test.'"' ;
if((isset($_GET["tag"])) && $_GET["tag"] == $test) {
echo ' checked="checked"';
}
echo '> '.$tag_names[$tag_ID].'<br>';
}
Function(wordpress documentation):
<?php checked( $checked, $current, $echo ); ?>
Example:
<input type='radio' name='tag' value='1' <?php checked(isset($variable)); ?>>variable
Another example(php):
$test=test;
echo "<input type='radio' name='tag' value='$test' checked( isset( $test ) ); >";
With escaping:
$tagslug = $tag_slug[$tag_ID];
echo '<input type="radio" name="tag" value=/"$tagslug/" checked( isset( $tagslug ) );>';
Another example without the wordpress function checked:
Paste it in here and test it
$test = "slug";
echo '<input type="radio" name="tag" value="$test"' ;
if (isset($test)) {
echo 'checked="checked"';
}
echo '>';
Try this
echo '<input type="radio" name="tag" value="'.$tag_slug[$tag_ID].'" '.if((isset($_POST["tag"])) && $_POST["tag"] == "oudere-kinderen") { echo "checked=checked";}.'> '.$tag_names[$tag_ID].'';