DeeEmm

Pragmatism in code

 HikaMarkets multi vendor capabilities are great but sometimes leave room for improvement. One area that is definitely in need of improving is the form validation for vendors adding products via the front end. (there is none).

If like me, you have removed the default category you will need to make sure that the vendor has selected at least one category so that their product is displayed. To check this is relatively simple. All that is needed is some basic javascript form validation.

First we need to detect when the form is submitted, this can be achieved by adding an 'onsubmit' event handler to the form declaration. We are going to use this to trigger a javascript function where we will do all of The heavy lifting.

When the form is submitted, the javascript function (we'll call it validateForm so that we can remember what it does) checks that a valid category has been submitted and if none is detected displays an alert box warning the vendor that they need to select a category or two. It then returns the user to the page without submitting.

Detecting that a valid category has been submitted is not easy as there are many possible categories and they may potentially change. The easiest way is to detect that nothing has been returned. To do this we use the 'undefined' property. 

Here's everything put together - simply add the following to the top of your HikaMarket - productmarket / form.php file you can add it directly underneath the javascript declaration that is already there.

<script type="text/javascript">
 function validateForm(){
  if (document.forms["hikamarket_form"]["data[product][categories][]"] === undefined){
      alert("Please Select one or more categories");
      exit;
  } else {
      return;
  }
  
}

</script>

Next you need to change  the 'onsubmit' handler. compare it with the one below, you will notice that the 'onsubmit' handler has been added to the end of the declaration. Simply change the one in your HikaMarket - productmarket / form.php file to match.

<form action="<?php hikamarket::completeLink('product');?>" method="post" name="hikamarket_form" id="hikamarket_products_form" enctype="multipart/form-data" onsubmit="return validateForm()">

You can also add validation checking for other form elements as well, simply check the value of the submitted element to make sure that a valid value is detected and if not raise an alert.