nested categories dropdown in magento - javascript

I have the following working code in magento frontend in a form for customer "add a product" functionality that Im developing:
Helper area:
public function getCategoriesDropdown() {
$categoriesArray = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name')
->addAttributeToSort('path', 'asc')
->addFieldToFilter('is_active', array('eq'=>'1'))
->load()
->toArray();
foreach ($categoriesArray as $categoryId => $category) {
if (isset($category['name'])) {
$categories[] = array(
'label' => $category['name'],
'level' =>$category['level'],
'value' => $categoryId
);
}
}
return $categories;
}
PHTML File:
<select id="category-changer" name="category-changer" style="width:150px;">
<option value="">--Select Categories--</option>
<?php
$_CategoryHelper = Mage::helper("marketplace")->getCategoriesDropdown();
foreach($_CategoryHelper as $value){
foreach($value as $key => $val){
if($key=='label'){
$catNameIs = $val;
}
if($key=='value'){
$catIdIs = $val;
}
if($key=='level'){
$catLevelIs = $val;
$b ='';
for($i=1;$i<$catLevelIs;$i++){
$b = $b."-";
}
}
}
?>
<option value="<?php echo $catIdIs; ?>"><?php echo $b.$catNameIs ?></option>
<?php
}
?>
</select>
this code generates a dropdown with categories and subcategories. like this one:
my main idea is to create n level nested chained dropdowns for subcategories like this example:
or this layout would be better:
any guidance or code example to modify the proposed php in order to include an ajax call, or javascript to generate those frontend chained frontends will be appreciated
brgds!

Here is my way:
In helper class, add method:
public function getCategoriesDropdown() {
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name')
->addAttributeToSort('path', 'asc')
->addFieldToFilter('is_active', array('eq'=>'1'));
$first = array();
$children = array();
foreach ($categories->getItems() as $cat) {
if ($cat->getLevel() == 2) {
$first[$cat->getId()] = $cat;
} else if ($cat->getParentId()) {
$children[$cat->getParentId()][] = $cat->getData();
}
}
return array('first' => $first, 'children' => $children);
}
In PHTML File:
<?php $tree = $this->helper('xxx')->getCategoriesDropdown(); ?>
<script type="text/javascript">
var children = $H(<?php echo json_encode($tree['children']) ?>);
function showCat(obj, level) {
var catId = obj.value;
level += 1;
if ($('cat_container_' + level)) {
$('cat_container_' + level).remove();
}
if (children.get(catId)) {
var options = children.get(catId);
var html = '<select id="cat_' + catId + '" onchange="showCat(this, ' + level + ')">';
for (var i = 0; i < options.length; i++) {
html += '<option value="' + options[i].entity_id + '">' + options[i].name + '</option>';
}
html += '</select>';
html = '<div id="cat_container_' + level + '">' + html + '</div>';
$('sub_cat').insert(html);
}
}
</script>
<select id="first_cat" onchange="showCat(this, 2)">
<?php foreach ($tree['first'] as $cat): ?>
<option value="<?php echo $cat->getId() ?>"><?php echo $cat->getName() ?></option>
<?php endforeach ?>
</select>
<div id="sub_cat"></div>

$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
/* You can play with this code */
echo '<select>';
echo getChildrenCategoryOptions($rootCategoryId);
echo '</select>';
/* You can play with this code */
function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();
if( $_categoryCollection->count() > 0 ) {
foreach($_categoryCollection as $_category) {
$html .= '<option value="'.$_category->getId().'">'.str_repeat("-", ($_category->getLevel() - 2)).$_category->getName().'</option>';
$html .= getChildrenCategoryOptions($_category->getId());
}
return $html;
}
else {
return '';
}
}

$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
$categoriesHierachy = getChildrenCategoryOptions($rootCategoryId);
function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();
if( $_categoryCollection->count() > 0 ) {
foreach($_categoryCollection as $_category) {
$array[$_category->getLevel()][$_category->getId()]['name'] = $_category->getName();
$array[$_category->getLevel()][$_category->getId()]['subcategories'] = getChildrenCategoryOptions($_category->getId());
}
return $array;
}
else {
return array();
}
}

Related

I can't save specific selected value. it saved all data from database

i am inserting multiple data. what happen is when i select a project from drop down list. it save all data from selection. please check the image below first
function sample($con){
$select = "SELECT * FROM project_tbl";
$select_result = mysqli_query($con,$select);
if (mysqli_num_rows($select_result)> 0) {
while ($row = mysqli_fetch_assoc($select_result)) {
echo "<option value=".$row['project_name'].">" .$row['project_name']."</option>";
}
}
}
*html codes (i used drop down list to populate data from database)
<td class="pro">
<select class="pro">
<option value=""><?php sample($con); ?></option>
</select>
</td>
*ajax codes (adding, saving and removing)
$(document).ready(function(){
var count = 1;
$('#add').click(function(){
count = count + 1;
var html_code = "<tr id='row"+count+"'>";
html_code += "<td class='pro'><select class='pro'><option value=''><?php sample($con); ?></option></select></td>";
html_code += "<td contenteditable='true' class='desc'></td>";
html_code += "<td contenteditable='true' class='comp'></td>";
html_code += "<td contenteditable='true' class='entry'></td>";
html_code += "<td contenteditable='true' class='remarks'></td>";
html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-outline-danger btn-xs remove' title='remove'><i class='fa fa-times' aria-hidden='true'></i></button></td>";
html_code += "</tr>";
$('#crud_table').append(html_code);
});
$(document).on('click', '.remove', function(){
var delete_row = $(this).data("row");
$('#' + delete_row).remove();
});
$('#save').click(function(){
var desc = [];
var pro = [];
var comp = [];
var entry = [];
var remarks = [];
$('.desc').each(function(){
desc.push($(this).text());
});
$('.pro').each(function(){
pro.push($(this).text());
});
$('.comp').each(function(){
comp.push($(this).text());
});
$('.entry').each(function(){
entry.push($(this).text());
});
$('.remarks').each(function(){
remarks.push($(this).text());
});
$.ajax({
url:"insert_inspection.php",
method:"POST",
data:{desc:desc, pro:pro, comp:comp, entry:entry, remarks:remarks},
success:function(data){
alert(data);
$("td[contentEditable='true']").text("");
$('select').prop('selectedIndex',0);
for(var i=2; i<= count; i++){
$('tr#'+i+'').remove();
}
}
});
});
});
Here is what happen when I save.
database
I am new in PHP.
insert_inspection.php
<?php
$con = mysqli_connect("localhost", "root", "", "pms");
if (isset($_POST["desc"])){
$desc = $_POST["desc"];
$pro = $_POST["pro"];
$comp = $_POST["comp"];
$entry = $_POST["entry"];
$remarks = $_POST["remarks"];
$query = '';
for($count = 0; $count<count($desc); $count++){
$desc_clean = mysqli_real_escape_string($con, $desc[$count]);
$pro_clean = mysqli_real_escape_string($con, $pro[$count]);
$comp_clean = mysqli_real_escape_string($con, $comp[$count]);
$entry_clean = mysqli_real_escape_string($con, $entry[$count]);
$remarks_clean = mysqli_real_escape_string($con, $remarks[$count]);
if($desc_clean != '' && $pro_clean != '' && $comp_clean != '' && $entry_clean != '' && $remarks_clean != ''){
$query .= 'INSERT INTO `inspection_tbl`(`description`, `project_name`, `completion`, `entry`, `remarks`) VALUES("'.$desc_clean.'", "'.$pro_clean.'", "'.$comp_clean.'", "'.$entry_clean.'", "'.$remarks_clean.'");
';
}
}
if($query != ''){
if(mysqli_multi_query($con, $query)){
echo 'Item Data Inserted';
}else{
echo 'Error';
}
}else{
echo 'All Fields are Required';
}
}
?>
it is saved as such because your select element only has one option value
modify it from:
<td class="pro"> <select class="pro"> <option value=""><?php sample($con); ?></option> </select> </td>
to:
<td class="pro">
<select class="pro">
<option value=""></option>
<?php sample($con); ?>
</select>
</td>
and modify your select element handler to push only your selected item
something like this:
$('.pro').each(function(){
if($(this).prop("selected")) {
pro.push($(this).text());
}
});
or modify this part to something like:
$(".pro > option:selected").each(function(){
pro.push($(this).text());
});

Javascript filter not filtering by selection only?

So I got this code and everytime I filter by selection it goes site.com/brands/brand+++red/ (example of trying to filter by brand + varietal). Is there a way to make it filter by the marked options only removing the extras "+'s" from the URL?.I tried adding several IF for each ID but I can't make it to remove the extra symbols from the URL. Thanks
<div>
<h4> TYPE </h4>
<?php $firstParent = $parents[2]; ?>
<?php $types = get_term_children( $firstParent->term_id, $taxonomy ); ?>
<select name="type" id="type">
<option value="">Choose type</option>
<?php foreach ( $types as $child ) {
$term = get_term_by( 'id', $child, $taxonomy ); ?>
<option value="<?php echo $term->slug; ?>"><?php echo $term->name; ?></option>
<?php } ?>
</select>
<br><br>
<h4> BRANDS </h4>
<?php $firstParent = $parents[0]; ?>
<?php $brands = get_term_children( $firstParent->term_id, $taxonomy ); ?>
<select name="brand" id="brand">
<option value="">Choose brand</option>
<?php foreach ( $brands as $child ) {
$term = get_term_by( 'id', $child, $taxonomy ); ?>
<option value="<?php echo $term->slug; ?>"><?php echo $term->name; ?></option>
<?php } ?>
</select>
<br><br>
<h4> REGION </h4>
<?php $firstParent = $parents[1]; ?>
<?php $regions = get_term_children( $firstParent->term_id, $taxonomy ); ?>
<select name="region" id="region">
<option value="">Choose region</option>
<?php foreach ( $regions as $child ) {
$term = get_term_by( 'id', $child, $taxonomy ); ?>
<option value="<?php echo $term->slug; ?>"><?php echo $term->name; ?></option>
<?php } ?>
</select>
<br><br>
<h4> VARIETAL </h4>
<?php $firstParent = $parents[3]; ?>
<?php $varietals = get_term_children( $firstParent->term_id, $taxonomy ); ?>
<select name="varietal" id="varietal">
<option value="">Choose varietal</option>
<?php foreach ( $varietals as $child ) {
$term = get_term_by( 'id', $child, $taxonomy ); ?>
<option value="<?php echo $term->slug; ?>"><?php echo $term->name; ?></option>
<?php } ?>
</select>
<?php endif;?>
<br>
<br>
<button type="button" id="filter">Apply</button>
</div>
<script type="text/javascript">
document.getElementById("filter").onclick = function () {
location.href = "<?php echo home_url();?>/brands/" +
document.getElementById("type").value + "+" + document.getElementById("brand").value + "+" +
document.getElementById("region").value + "+" + document.getElementById("varietal").value;
};
<script type="text/javascript">
document.getElementById("filter").onclick = function() {
var type = document.getElementById("type")
var brand = document.getElementById("brand")
var region = document.getElementById("region")
var varietal = document.getElementById("varietal")
var q = '';
if (type) {
q = document.getElementById("type").value + '+'
}
if (brand) {
q = q + document.getElementById("brand").value + '+';
}
if (region) {
q = q + document.getElementById("region").value + '+';
}
if (varietal) {
q = q + document.getElementById("region").value;
}
location.href = "<?php echo home_url();?>/brands/" + q;
};
</script>
Your variables contain the DOM elements, not their values; these will always be true (unless the DOM elements don't exist). You need to use .value.
And instead of concatenating strings, put all the items you want in an array, then use .join() to create a string with + between them.
document.getElementById("filter").onclick = function() {
var type = document.getElementById("type").value
var brand = document.getElementById("brand").value
var region = document.getElementById("region").value
var varietal = document.getElementById("varietal").value
var q = [];
if (type) {
q.push(type);
}
if (brand) {
q.push(brand);
}
if (region) {
q.push(region);
}
if (varietal) {
q.push(varietal);
}
location.href = "<?php echo home_url();?>/brands/" + q.join("+");
};
You need to check if the value is empty/null for each field, then append, or not, to the url. Better using an array and then "implode" or "join" by your string +:
var url = "<?php echo home_url();?>/brands/";
var urlParams = [];
if (document.getElementById("type").value != '') {
urlParams.push(document.getElementById("type").value);
}
if (document.getElementById("brand").value != '') {
urlParams.push(document.getElementById("brand").value);
}
if (document.getElementById("region").value != '') {
urlParams.push(document.getElementById("region").value);
}
if (document.getElementById("varietal").value != '') {
urlParams.push(document.getElementById("varietal").value);
}
location.href = url + urlParams.join('+');

JavaScript to change a multi level <select> into accordion

in my item post page, their is an for selecting main category and than after selecting it shows relevant sub category.
i want to change this in to a accordion. please help me how to change this. so when a user come to my website and try to post ad he should be shown accordion for selecting the main category and sub category. please help me to achieve this by modify the code or using java-script to achieve this.
the code `
$categoryID = Params::getParam('catId');
if( osc_item_category_id() != null ) {
$categoryID = osc_item_category_id();
}
if( Session::newInstance()->_getForm('catId') != '' ) {
$categoryID = Session::newInstance()->_getForm('catId');
}
$subcategoryID = '';
if( !Category::newInstance()->isRoot($categoryID) ) {
$subcategoryID = $categoryID;
$category = Category::newInstance()->findRootCategory($categoryID);
$categoryID = $category['pk_i_id'];
}
if($categories == null) {
if(View::newInstance()->_exists('categories')) {
$categories = View::newInstance()->_get('categories');
} else {
$categories = osc_get_categories();
}
}
if ($item == null) { $item = osc_item(); }
$subcategory = array();
?>
<select id="parentCategory" name="parentCatId">
<option value=""><?php _e('Select a category', 'modern'); ?></option>
<?php foreach($categories as $_category) {
$selected = ( (isset($item["fk_i_category_id"]) && $item["fk_i_category_id"] == $_category['pk_i_id']) || (isset($categoryID) && $categoryID == $_category['pk_i_id']) );
if($selected) { $subcategory = $_category; };
echo '<option value="'.$_category['pk_i_id'].'" '.($selected ? 'selected="selected"' : '' ).'>'.$_category['s_name'].'</option>';
} ?>
</select>
<select id="catId" name="catId">
<?php
if(!empty($subcategory)) {
if( count($subcategory['categories']) > 0 ) {
echo '<option value="">'.__('Select Subcategory', 'modern').'</option>';
foreach($subcategory['categories'] as $c) {
$selected = ( (isset($item["fk_i_category_id"]) && $item["fk_i_category_id"] == $c['pk_i_id']) || (isset($subcategoryID) && $subcategoryID == $c['pk_i_id']) );
echo '<option value="'.$c['pk_i_id'].'" '.($selected ? 'selected="selected"' : '' ).'>'.$c['s_name'].'</option>';
}
} else {
echo '<option value="'.$categoryID.'" >'._e('No Subcategory', 'modern').'</option>';
}
} else {
echo '<option value="">'._e('Select Subcategory', 'modern').'</option>';
}
?>
</select>
<script type="text/javascript" charset="utf-8">
<?php
foreach($categories as $c) {
if( count($c['categories']) > 0 ) {
$subcategory = array();
for($i = 0; $i < count($c['categories']); $i ) {
$subcategory[] = array($c['categories'][$i]['pk_i_id'], $c['categories'][$i]['s_name']);
}
printf('var categories_%1$s = %2$s;', $c['pk_i_id'], json_encode($subcategory));
echo PHP_EOL;
}
}
?>
$(document).ready(function(){
$("#parentCategory").bind('change', function(){
var categoryID = $(this).val();
if( categoryID == 0 ) {
var options = '<option value="' categoryID '" selected=""><?php _e('No Subcategory', 'modern'); ?></option>';
}
categories = window['categories_' categoryID];
if( categories==null || !$.isArray(categories) ) {
var options = '<option value="' categoryID '" selected=""><?php _e('No Subcategory', 'modern'); ?></option>';
} else {
var options = '<option value="' categoryID '" selected=""><?php _e('Select Subcategory', 'modern'); ?>...</option>';
$.each(categories, function(index, value){
options = '<option value="' value[0] '">' value[1] '</option>';
});
};
$('#catId').html(options);
$("#catId").next("a").find(".select-box-label").text('Select a Sub Category...');
$("#catId").change();
$("div#uniform-catId.selector").css('visibility', 'visible');
});
// In case of error and Category already chosen, let's show the Subcategory selector
if($("div#uniform-parentCategory.selector select").val()) {
$("div#uniform-catId.selector").css('visibility', 'visible');
}
});
</script>
<?php
}
?>`
If this is related to osclass, in item-post.php from bender (for example), use
<?php ItemForm::category_select(null, null, __('Select a category', 'bender')); ?>
instead of
<?php ItemForm::category_multiple_selects(); ?>
PS. This is not a js solution.

How to put validation on a dynamic dropdown when inserting in PHP?

I'm constructing a survey and I have a textbox that generates dynamic dropdowns based on user input which displays the same data.
This is the script
<script>
function load_questions(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php??main=1&subcategory="+document.getElementById("subcategorydd").value +"&cnt="+document.getElementById("q_num").value,false);
xmlhttp.send(null);
document.getElementById("question").innerHTML=xmlhttp.responseText;
}
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
</script>
This is the insert code when I'm creating the survey
<?php
$con = mysqli_connect("localhost","root","","imetrics");
if(isset($_POST['submit'])){
$title = $_POST['surveytitle'];
$catdd = $_POST['catdd'];
$subcatdd = $_POST['subcatdd'];
$gender = $_POST['gender'];
$age = $_POST['age'];
$occupation = $_POST['occupation'];
$occupationtwo = $_POST['occupdd'];
$relstatus = $_POST['relationshipstatus'];
$q_num = $_POST['q_num'];
$insert = mysqli_query($con, "INSERT INTO `surveyform` (`surveytitle`,`surveycategory`,`surveysubcategory`,`gender`,`age`,`occupation`,`occupation_status`,`status`) VALUES ('$title','$catdd','$subcatdd','$gender','$age','$occupation','$occupationtwo','$relstatus')");
if(!$insert){
echo mysqli_errno();
}
else{
$getMaxID = mysqli_query($con, "SELECT MAX(survey_id) as maxid FROM surveyform");
$row_2 = mysqli_fetch_array($getMaxID);
$survey_id = $row_2[0];
for( $a = 1; $a <= $q_num; $a++)
{
mysqli_query($con, "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")");
//echo "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")";
}
echo '<script language="javascript">';
echo 'alert("Survey Created!")';
echo '</script>';
}
}
?>
And this is my dropdown code
if($question !="" && $cnt!="" && $addQues!="yes" && $main != 1){
$i = 0;
for ($i = 1; $i <= $cnt; $i++)
{
$query=mysqli_query($con, "SELECT * FROM question WHERE question_subcat = $question ");
echo "<b>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control-static' name='question_dropdowns".$i."'>";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
}
echo "</select>";
echo "<br />";
}
echo "<div id='insertQuesHere".$i."'></div>";
echo "<a href='#add_question' onclick='return addQues();'>Add Question</a>";
}
here's my submit button
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
What's the validation code that will prevent me from inserting if the data chosen from the dropdown is the same? For example I generated 2 dropdowns and I chose the same datas from the dropdown, what's the validation code for it?
Please call checkValues method your submit button click
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
checkValues method below :
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
Also , you can see an example Example

Unable to insert Ajax return into HTML

I'm trying to use a PHP file to process serialized info from an Ajax request. I want to send back the value of each form field to be further manipulated by javascript (inserted into a div). The result is not being inserted into the HTML. When I alert the result I get {"return":["<p>form value for name<\/p>","<p>form value for description<\/p>"]} Any suggestions?
EDIT: Updated question with relevant HTML and revised PHP code.
HTML:
<div class="col-md-4">
<h5>Heading</h5>
<div id="formBasicResults"></div>
</div>
Javascript:
.on('success.form.fv', function (e) {
e.preventDefault();
var $form = $(e.target);
var bv = $form.data('formValidation');
$.post($form.attr('action'), $form.serialize())
.done(function (result) {
$('#formBasicResults').html(result.responseText);
alert(result);
},'json');
});
PHP:
if (!isset($_SESSION)) {
session_start();
if (!isset($_SESSION['token'])) {
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
$_SESSION['token_time'] = time();
} else {
$token = $_SESSION['token'];
}
}
foreach($_POST as $key = > $value) {
$temp = is_array($value) ? $value : trim($value);
$_SESSION[$key] = $temp;
}
$expected = array(
'name' = > 'string',
'description' = > 'string',
);
foreach($expected AS $key) {
if (!empty($_POST[$key])) {
$ {$key} = $_POST[$key];
} else {${$key} = NULL;
}
}
foreach($expected AS $key = > $type) {
if (empty($_POST[$key])) {
$ {$key} = NULL;
continue;
}
if (!isset($ {
$key})) {
$ {$key} = NULL;
}
}
function safe( $value ) {
htmlentities( $value, ENT_QUOTES, 'utf-8' );
return ($value);
}
$name = $_POST['name'];
$description = $_POST['description'];
$return['result']=array();
if(!empty($name)){$return['result'][]= '<p>' . safe($name) . '</p>';}
if(!empty($description)){$return['result'][]= '<p>' . safe($description) . '</p>';}
echo json_encode($return);
try something like this:
$('#formBasicResults').html(result['return'][0]);
or
$('#formBasicResults').html(result['return'][1]);
Instead of this:
if ($_POST['token'] == $_SESSION['token'])
{$return['return']=array();
if(!empty($_POST['name'])){$return['return'][] = '<p>' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8') . '</p>';
if(!empty($_POST['description'])){$return['return'][] = '<p>' . htmlentities($_POST['description'], ENT_QUOTES, 'UTF-8') . '</p>';}
echo json_encode($return); }}
do this:
$return['responseText']='';
if ($_POST['token'] == $_SESSION['token'])
{
if(!empty($_POST['name'])){
$return['responseText'] .= '<p>' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8') . '</p>';
if(!empty($_POST['description'])){
$return['responseText'] .= '<p>' . htmlentities($_POST['description'], ENT_QUOTES, 'UTF-8') . '</p>';}
}
}
echo json_encode($return);

Categories

Resources