The Date stored in my database is like '2018-09-15 10:34:09',i want result of search in '15-09-2018' Format.I'm using Kartik datepicker to select date - stored-procedures

I'm new in programming and I'm confused at one point. I'm using kartik datepicker to search date from table.In my table the date is stored in '2018-09-15 10:34:09' format. I'm using a stored procedure here and when I enter date (in format: 15-9-2018), I want to show some results.
My controller:
<?php
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\Functions;
use backend\models\Meetmelicence;
use backend\models\MeetmelicenceSearch;
class MeetmelicenceController extends BackendController
{
public function actionIndex($redirect = '')
{
$searchModel = new MeetmelicenceSearch();
$model = new Meetmelicence();
if(isset($_GET['MeetmelicenceSearch']))
{
$searchModel->attributes = $_GET['MeetmelicenceSearch'];
}
if($redirect == 'success')
{
Yii::$app->session->setFlash('success', 'Import data processed
successfully.');
}
$transaction_id = $searchModel->transaction_id;
$transactionmodel = $this->findModeltransactionmodel($transaction_id);
return $this->render('index', [
'searchModel' => $searchModel,
'model' => $model,
'transactionmodel' =>$transactionmodel,
]);
}
protected function findModeltransactionmodel($id)
{
if (($model = Payment::findOne(['transaction_id' => $id])) !== null) {
return $model;
}
else {
return false;
}
}
}
Model:
<?php
namespace backend\models;
use Yii;
use backend\models\Backendcommon;
class Meetmelicence extends Backendcommon
{
public $transaction_id;
public $transaction_date;
public $new_expiry_date;
public static function tableName()
{
return 'meet_me_licence_master';
}
public function rules()
{
return [
[['created_on', 'updated_on','unit_id','unit_user_id','isEmail','recieve_calls','transaction_id','transaction_date','new_expiry_date','user_licence_status','remarks'], 'safe'],
[['licence_number','status'],'required'],//,'licence_password'
[['transaction_id'],'required'],
];
}
}
Search model:
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\StaffCategory;
use yii\data\SpDataProvider;
class MeetmelicenceSearch extends Meetmelicence
{
public function rules()
{
return [
[['new_expiry_date','transaction_id','new_expiry_date','transaction_date',], 'safe'],
];
}
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
public function search()
{
$arrParams = array();
$arrParams['v_private_key'] = \Yii::$app->params['private_db_key'];
$object_xml_array['transaction_date'] = $this->transaction_date;
$object_xml_array['new_expiry_date']=$this->new_expiry_date;
$xml = new \SimpleXMLElement('<CustomXML/>');
$this->function_model->_array_to_xml($object_xml_array, $xml, 0);
$object_xml_array = $xml->asXML();
$final_array_xml = urldecode($object_xml_array);
$arrParams['v_object_xml'] = $final_array_xml;
$dataProvider = new SpDataProvider([
'spName' => 'meet_me_licence_list',
'params' => $arrParams,
'sort' => [
'attributes' => [
'transaction_date' => [
'asc' => ['transaction_date' => SORT_ASC, 'transaction_date' => SORT_ASC],
'desc' => ['transaction_date' => SORT_DESC, 'transaction_date' => SORT_DESC],
'default' => SORT_ASC,
'label' => 'Transaction Date',
],
'new_expiry_date' => [
'asc' => ['new_expiry_date' => SORT_ASC, 'new_expiry_date' => SORT_ASC],
'desc' => ['new_expiry_date' => SORT_DESC, 'new_expiry_date' => SORT_DESC],
'default' => SORT_ASC,
'label' => 'New Transaction Expiry Date',
],
],
'pagination' => [
'pageSize' => 20,
],
]);
return $dataProvider;
}
}
My index file:
<?php
<div class="container">
<div class="panel panel-default">
<div class="panel-body" style="padding:0px">
<?php Pjax::begin(['timeout' => 500000,'enablePushState'=>false]); ?>
<?= GridView::widget([
'dataProvider' => $searchModel->search(),
'filterModel' => $searchModel,
// 'layout' => '{items}{pager}',
'layout' => '{items}{pager}{summary}',
'pager' => [
'firstPageLabel' => 'First',
'lastPageLabel' => 'Last'
],
'columns' =>
[
'attribute'=> 'transaction_date',
'filter'=>DatePicker::widget([
'attribute'=> 'transaction_date',
'model' => $searchModel,
'type' => DatePicker::TYPE_COMPONENT_APPEND,
// 'type' => DatePicker::TYPE_COMPONENT_PREPEND,
// 'type' => DatePicker::TYPE_INPUT,
// 'type' => DatePicker::TYPE_BUTTON,
'options' => ['id'=> 'searchmodel_transaction_date',],
// 'value'=>'23-Feb-1982',
'pluginOptions' => [
'autoclose' => true,
'format' => 'dd-M-yyyy',
'todayHighlight' => true,
]
]),
'contentOptions' => [ 'style' => 'width: 80%;' ],
],
[
'attribute'=> 'new_expiry_date',
'filter'=>DatePicker::widget([
'attribute'=> 'new_expiry_date',
'model' => $searchModel,
'type' => DatePicker::TYPE_COMPONENT_APPEND,
'options' => ['id'=> 'searchmodel_new_expiry_date',],
'value'=>'10/05/2022',
'pluginOptions' => [
'autoclose' => false,
'format' => 'dd-M-yyyy',
'todayHighlight' => true,
]
]),
'contentOptions' => [ 'style' => 'width: 80%;' ],
],
],
]); ?>
<?php Pjax::end(); ?>
</div>
</div>
</div>
My stored procedure:
DELIMITER $$
USE `fermax_crm_local_4_31`$$
DROP PROCEDURE IF EXISTS `meet_me_licence_list`$$
CREATE DEFINER=`dbfermaxcrm`#`%` PROCEDURE `meet_me_licence_list`(
IN v_private_key VARCHAR(100),
IN v_licence_number VARCHAR(255),
IN v_object_xml TEXT,
IN v_Sort TEXT,
IN v_limit INT,
IN v_pageIndex INT)
BEGIN
/*
*/
DECLARE v_Select TEXT DEFAULT "";
DECLARE v_Where TEXT DEFAULT " WHERE 1";
DECLARE v_From TEXT DEFAULT "";
DECLARE v_OrderBy TEXT DEFAULT "";
DECLARE v_QueryLimit TEXT DEFAULT "";
DECLARE v_group_by TEXT DEFAULT "";
DECLARE v_having TEXT DEFAULT "";
DECLARE
v_transaction_date,v_new_expiry_date DEFAULT "";
DECLARE v_transaction_id INT DEFAULT 0;
SET SESSION group_concat_max_len = 1000000000;
SET v_transaction_date = EXTRACTVALUE(v_object_xml, '//transaction_date[$#1]');
SET v_new_expiry_date = EXTRACTVALUE(v_object_xml, '//new_expiry_date[$#1]');
SET v_transaction_id = EXTRACTVALUE(v_object_xml, '//v_transaction_id[$#1]');
CALL add_query_log(0,0,'meet_me_licence_list',CONCAT("CALL meet_me_licence_list('"
,IFNULL(v_private_key,''),"','"
,IFNULL(v_licence_number,''),"','"
,IFNULL(v_object_xml,''),"','"
,IFNULL(v_Sort,''),"','"
,IFNULL(v_limit,''),"','"
,IFNULL(v_pageIndex,''),"',"
,");"
));
SET v_Select = CONCAT(" SELECT
mmlm.meet_me_licence_id
,mmlm.most_recent_audit_log
,get_date_string(mmlt.transaction_date,1,1, ' %d %b %Y %h:%i %p ') AS transaction_date
,get_date_string(mmlt.new_expiry_date ,1,1, ' %d %b %Y %h:%i %p ') AS new_expiry_date
");
SET v_From = CONCAT(" FROM meet_me_licence_master AS mmlm
LEFT JOIN meet_me_licence_transaction mmlt
ON mmlm.meet_me_licence_id= mmlt.meet_me_licence_id
LEFT JOIN unit un
ON CAST(un.unit_id AS CHAR) = CAST(mmll.unit_id AS CHAR)
");
SET v_Where = CONCAT(v_Where," AND mmlm.status != 3 ");
IF (IFNULL(v_transaction_date,'') != '') THEN
SET v_Where = CONCAT(v_Where," AND mmlt.transaction_date ='", v_transaction_date,"' ");
END IF;
IF (IFNULL(v_new_expiry_date,'') != '') THEN
SET v_Where = CONCAT(v_Where," AND mmlt.new_expiry_date = '",v_new_expiry_date,"' ");
END IF;
-- IF (v_sort_order != '') THEN
-- SET v_Where = CONCAT(v_Where," AND lower(c.sort_order) LIKE '%",v_sort_order,"%' ");
-- END IF;
SET v_group_by = CONCAT(" GROUP BY mmlm.meet_me_licence_id ");
SET #rec_Query = CONCAT(v_Select
,v_From
,v_Where
,v_group_by
,v_having
);
-- SET #cnt_Query = CONCAT("Select Count(*) INTO #o_RecCount FROM (",#rec_Query,") AS tmp");
SET #cnt_Query = CONCAT("Select Count(*) as o_RecCount FROM (",#rec_Query,") AS tmp");
-- IF(v_Sort != "") THEN
/*SET v_OrderBy = CONCAT("
ORDER BY CASE WHEN IFNULL(mmlm.updated_on,'0000-00-00 00:00:00') != '0000-00-00 00:00:00' then mmlm.updated_on
ELSE mmlm.`created_on` END DESC
");*/
-- END IF;
IF(v_Sort != "") THEN
SET v_OrderBy = CONCAT(" ORDER BY ",v_Sort);
ELSE
SET v_OrderBy = CONCAT("
ORDER BY CASE WHEN IFNULL(mmlm.updated_on,'0000-00-00 00:00:00') != '0000-00-00 00:00:00' then mmlm.updated_on
ELSE mmlm.`created_on` END DESC
");
END IF;
IF (v_PageIndex) > 0 THEN
SET v_QueryLimit = CONCAT(" LIMIT ", v_limit, "," , v_pageIndex);
END IF;
SET #vv_Query= CONCAT(v_Select
,v_From
,v_Where
,v_group_by
,v_OrderBy
,v_QueryLimit);
SELECT #vv_Query;
PREPARE s1 FROM #vv_Query;
EXECUTE s1;
PREPARE c2 FROM #cnt_Query;
EXECUTE c2;
-- select #cnt_Query;
END$$
DELIMITER ;

Related

How to fix 'The input was not found in the haystack' in ZF2?

I have an issue in my code which I can't resolve. I'm using Zend framework 2.4 and I wrote a form but as soon as I validate it, I got the error The input was not found in the haystack. This are the 3 input where I got the error:
$this->add(array(
'name' => 'ACTIVITE1',
'type' => 'Zend\Form\Element\Select',
'required' => 'required',
'options' => array(
'value_options' => array(
'Choisir l\'activité'
),
'disable_inarray_validator' => false,
),
'attributes' => array(
'class' => 'form-control',
'id' => 'select-session1'
)
));
$this->add(array(
'name' => 'ACTIVITE2',
'type' => 'Zend\Form\Element\Select',
'required' => 'required',
'options' => array(
'value_options' => array(
'Choisir l\'activité'
)
),
'disable_inarray_validator' => false,
'attributes' => array(
'class' => 'form-control',
'id' => 'select-session2'
)
));
$this->add(array(
'name' => 'ACTIVITE3',
'type' => 'Zend\Form\Element\Select',
'required' => 'required',
'options' => array(
'value_options' => array(
'Choisir l\'activité'
)
),
'disable_inarray_validator' => false,
'attributes' => array(
'class' => 'form-control',
'id' => 'select-session3'
)
));
I saw in other form that I should put 'disable_inarray_validator' => false but this doesn't work too.
Of course it's not working.
That message comes from the \Zend\Validator\InArray and essentially, it means: "your user is doing something hacky with your select, pay attention".
An exemple would be a Select Preferred fruit with two options, like "Banana" and "Ananas", but the user "hacks" the select and sends to the server the value "Audi". The InArray validator is really important and shouldn't be disabled (well, only in a few exceptions..).
Now, why are you getting this error? The answer is... You didn't told what are the select options. You created a Select, but you didn't specified what are its options. You put the label/placeholder at the place of the options. A correct Select would be:
$this->add(array(
'name' => 'ACTIVITE1',
'type' => 'Zend\Form\Element\Select',
'required' => 'required',
'options' => array(
'value_options' => array(
1 => 'Fitness',
2 => 'Parcour',
3 => 'Velo',
4 => 'Tapis roulant',
// ... and so on
)
),
'attributes' => array(
'class' => 'form-control',
'id' => 'select-session1',
'placeholder' => "Choisir l'activité"
)
));
What is "weird" is the fact that you are filling something in an empty select, and my question then is: why?
Selects are (typically) there for a predefined list of values. If you want to allow your users to fill a custom text, then you should consider to create a Text field with the autocomplete option.
Edit: select with values from DB
If you want to create a select with a list of options that come from the database, the route is a bit more complex, but once you've learned how to do it, it will become way easier.
PAY ATTENTION: this will not be a "copy&paste solution". Since I'm not having access to your code, I'm making up names (classes, namespaces, methods, variables) just to create a complete example :)
First off, you must create a custom element. In this case, it will be a custom select:
namespace Yournamespace;
use Zend\Form\Element\Select;
use Yournamespace\ActivityMapper;
class ActivitySelect extends Select {
protected $activityMapper;
public function __construct(ActivityMapper $activityMapper, $name = null, $options = []) {
parent::__construct($name, $options);
$this->activityMapper = $activityMapper;
}
public function init() {
$valueOptions = [];
foreach ($this->activityMapper->fetchAll() as $activity) {
$valueOptions[$activity->getActivityId()] = $activity->getActivityName();
}
$this->setValueOptions($valueOptions);
}
}
What is really important here is that you must instantiate your element (options, classes, and so on..) inside init method.
Since this element has a dependency (ActivityMapper), you'll have to create a factory for this element:
namespace Yournamespace;
use Zend\ServiceManager\Factory\FactoryInterface;
use \Interop\Container\ContainerInterface;
class ActivitySelectFactory implements FactoryInterface {
public function __invoke(ContainerInterface $container, $requestedName, array $options = null): object {
$activityMapper = $container->get(\Yournamespace\ActivityMapper::class);
return \Yournamespace\ActivitySelect($activityMapper);
}
}
This factory must be added in the configuration, more precisely, inside module.config.php:
return [
// ...
'form_elements' => [
'factories' => [
\Yournamespace\ActivitySelect::class => \Yournamespace\ActivitySelectFactory::class,
]
]
// ...
];
Now, you must modify your form too. All elements must be added to form inside init method, and not inside the constructor:
namespace Yournamespace;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
class ActivityForm extends Form implements InputFilterProviderInterface {
public function init() {
parent::init();
// ...
$this->add([
'name' => 'ACTIVITE1',
'type' => \Yournamespace\ActivitySelect::class,
'attributes' => [
'class' => 'form-control',
'id' => 'select-session1',
'required' => true, // This will work only clientside, don't forget the inputfilter!
'placeholder' => 'Choisir l\'activité',
],
'options' => [
'label' => 'Choisir l\'activité',
]
]);
// ...
}
public function getInputFilterSpecification() {
// ...
$inputFilter[] = [
'name' => 'ACTIVITE1',
'required' => true
];
// ...
return $inputFilter;
}
}
Finally, you'll have to modify your controller too, because you need to retrieve the form from the FormElementManager:
namespace Yournamespace;
use Zend\Form\FormElementManager;
class YourController extends AbstractActionController {
private $formManager;
public function __construct(FormElementManager $formManager) {
$this->formManager = $formManager;
}
public function choisirActiviteAction(){
// ...
$form = $this->formManager->get(\Yournamespace\ActivityForm::class);
// ...
}
}
A next nice step would be to create a controller plugin for the $formManager, instead of making it as a dependency of each controller, but this is a different problem..
thanks for your answer! I understand what you mean but i did this because i don't want to control the select because i can't control all the possible options.
Because the options are from a database, i get them doing an AJAX request and i add all the option to the select in the view. So the options can vary and are not fixed.
Here is my AJAX request :
$("#input-dtNaissance").change(function() {
$.when($(".activites-options").remove()).then(function() {
if ($("#input-dtNaissance").val() != " ") {
//on supprime les anciennes activités proposées au cas où il y en ai
var year = $("#input-dtNaissance").val().substring(0,4);
if (year == "") {
year = 1;
}
// si date supprimée/réinitialisée
if (year == 1) {
// on supprime les activités proposées du select
$(".activites-options").remove();
} else {
$.getJSON("http://localhost/ecoleMunicipalSport/app/public/activite/listActivitySession1/" + year, function(data) {
data.forEach(element => {
var option = "<option value='" + element.ID_ACTIVITES + "' class='activites-options'>" + element.activite[0] + element.activite.substring(1).toLowerCase() + " avec " + element.INTERVENANT + " - " + element.HORAIREDEB + "/" + element.HORAIREFIN + " (" + element.site[0] + element.site.substring(1).toLowerCase() + ")" + "</option>";
$("#select-session1").append(option);
});
});
$.getJSON("http://localhost/ecoleMunicipalSport/app/public/activite/listActivitySession2/" + year, function(data) {
data.forEach(element => {
var option = "<option value='" + element.ID_ACTIVITES + "'class='activites-options'>" + element.activite[0] + element.activite.substring(1).toLowerCase() + " avec " + element.INTERVENANT + " - " + element.HORAIREDEB + "/" + element.HORAIREFIN + " (" + element.site[0] + element.site.substring(1).toLowerCase() + ")" + "</option>";
$("#select-session2").append(option);
});
});
$.getJSON("http://localhost/ecoleMunicipalSport/app/public/activite/listActivitySession3/" + year, function(data) {
data.forEach(element => {
var option = "<option value='" + element.ID_ACTIVITES + "' class='activites-options'>" + element.activite[0] + element.activite.substring(1).toLowerCase() + " avec " + element.INTERVENANT + " - " + element.HORAIREDEB + "/" + element.HORAIREFIN + " (" + element.site[0] + element.site.substring(1).toLowerCase() + ")" + "</option>";
$("#select-session3").append(option);
});
});
}
}
});
})
I know that it's not very safety and if you have a better solution with more security i'm open to the propositions.
Good evening.
PS : Sorree faur my terribl anglish :)

ZF2 - Allow an empty input file on submit

I have a form that allows a user to edit his information and upload an image. The image upload is optional but when I submit the form, I always have an error telling me that the image has not been uploaded.
Here is the partial fieldset code:
public function init() {
$this->add([
'name' => 'avatar',
'type' => 'file',
'attributes' => [
'id' => 'avatar',
'class' => 'input-file',
'accept' => 'image/*'
],
'options' => [
'label' => 'avatar',
]
]);
}
This fieldset implements InputFilterProviderInterface, so here is the code:
public function getInputFilterSpecification() {
return [
'avatar' => [
'type' => '\Zend\InputFilter\FileInput',
'allow_empty' => true,
'required' => false,
'validators' => [
[
'name' => 'FileExtension',
'options' => [
'extension' => ['jpg, jpeg, png'],
'message' => 'wrong_type_file'
]
],
[
'name' => 'FileSize',
'options' => [
'max' => '2MB',
'message' => 'file_too_large'
]
]
],
],
];
}
Despite the fact that this field is not required and allow_empty option is true, when I submit the form and debug the value, I still have validation that fails and this as my debug value:
'avatar' =>
array (size=5)
'name' => string '' (length=0)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 4
'size' => int 0
Do you know how could I validate my form event when no file is downloaded?
Thanks in advance for your answers!
EDIT 1: Here are the messages returned by the form after submission:
'avatar' =>
array (size=2)
'fileExtensionNotFound' => string 'Extension d'image non admise (.jpg, .jpeg, .png seulement)'
'fileSizeNotFound' => string 'Le fichier est trop volumineux, 2097152 maximum.' (length=48)
EDIT 2: the action in the controller:
$prg = $this->fileprg($form);
if ($prg instanceof Response) {
return $prg;
} elseif (is_array($prg)) {
$data = $form->getData();
if ($form->isValid()) {
if ($data['person']['file']) {
// #TODO upload file
}
if (!$this->personMapper->updatePerson($data)) {
$this->flashMessenger()->addErrorMessage($this->translator()->translate('error_occurs_backup'));
} else {
$this->flashMessenger()->addSuccessMessage($this->translator()->translate('data_saved'));
}
} else {
// #TODO file error management
\var_dump('not valid');
\var_dump($form->getMessages());
}
}

prestashop category / subcategory make cms 404 error

I am working with prestashop in a local environment and then set up a store, the problem that I have emerged is the following.
Buy the module to remove the IDs of URLs: Module Pretty URLs and works perfect.
then I want to show the URL of the subcategories the category parent, example: example.com/women/jeans
that achieve it using the following code, modifying the file override/classes/dispatcher.php
'category_rule' => array(
'controller' => 'category',
'rule' => 'categories:/}{rewrite}',
'keywords' => array(
'id' => array('regexp' => '[0-9]+'),
'rewrite' => array('regexp' => '[_a-zA-Z0-9-\pL]*', 'param' => 'category_rewrite'),
'categories' => array('regexp' => '[_a-zA-Z0-9-\pL]*'),
'meta_keywords' => array('regexp' => '[_a-zA-Z0-9-\pL]*'),
'meta_title' => array('regexp' => '[_a-zA-Z0-9-\pL]*'),
),
),
In the Prestashop admin adding {categories:/}{rewrite} to the SEO/URLs of the categories.
file override/classes/Link.php
public function getCategoryLink($category, $alias = null, $id_lang = null, $selected_filters = null, $id_shop = null, $relative_protocol = false)
{
if (!$id_lang) {
$id_lang = Context::getContext()->language->id;
}
$url = $this->getBaseLink($id_shop, null, $relative_protocol).$this->getLangLink($id_lang, null, $id_shop);
if (!is_object($category)) {
$category = new Category($category, $id_lang);
}
$params = array();
$params['id'] = $category->id;
$params['rewrite'] = (!$alias) ? $category->link_rewrite : $alias;
$params['meta_keywords'] = #Tools::str2url($category->meta_keywords);
$params['meta_title'] = #Tools::str2url($category->meta_title);
$selected_filters = is_null($selected_filters) ? '' : $selected_filters;
if (empty($selected_filters)) {
$rule = 'category_rule';
} else {
$rule = 'layered_rule';
$params['selected_filters'] = $selected_filters;
}
$cats = array();
foreach ($category->getParentsCategories() as $cat){
if (!in_array($cat['id_category'], array(1, 2, $category->id)))//remove root, home and current category from the URL
{
$cats[] = $cat['link_rewrite'];
$params['categories'] = implode('/', array_reverse($cats));
}
}
$r_url = $url.Dispatcher::getInstance()->createUrl($rule, $id_lang, $params, $this->allow, '', $id_shop);
return $r_url;
}
But to do this all the pages CMS throw me a 404, not that it can be.

Cakephp 3 - Create full url

What I like to do is creating a full url.
Controller = 'A'
Action = 'doSomething'
param1 = $id
param2 = $id2
What I currently get is:
mydomain.com/A/doSomething?param1=X&param2=XX
What I want is:
mydomain.com/A/doSomething/X/XX
Code:
$message = 'Test: '. Router::url([
"controller" => "A",
"action" => "doSomthing",
"param1" => $id,
"param2" => $id2,
'_full' => true
]);
$id1 = 'id1';
$id2 = 'id2';
$url= Router::url([
"controller" => "A",
"action" => "doSomething",
$id1,
$id2,
'_full' => true
]);
debug($url);
Outputs:
'http://host/a/do-something/id1/id2'
Try:
public function doSomthing($param1, $param2)
{
#your code here
}

ZF2 - Form creation missing validators

I am having a little trouble adding validators to a ZF2 form object. I an building a form from a schema set in a database so I can validate a set of user input quickly.
This is the code that generates the form object
//initialise the form
$form = new Form();
//need to loop through the schema to create the form
for($i=0; $i < count($schema); $i++)
{
$form_options = array();
//add the basics to the form
$form_options['name'] = $schema[$i]['field_name'];
$form_options['type'] = $schema[$i]['field_type'];
//check if this is a required field
if($schema[$i]['is_required'] == 'true')
{
$form_options['required'] = true;
}
//add functions to filter the input form
$function_filters = explode(',', $schema[$i]['function_filter']);
if(!empty($function_filters))
{
$filters = array();
for($j=0; $j < count($function_filters); $j++)
{
$filters = array('name' => $function_filters[$j]);
}
$form_options['filters'] = $filters;
}
//add validators to the field array
$validators = array();
if(!is_null($schema[$i]['min_length']) && !is_null($schema[$i]['max_length']))
{
$validators[] = array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => (int) $schema[$i]['min_length'],
'max' => (int) $schema[$i]['max_length'],
)
);
}
//our regex validator if it exists
if(!is_null($schema[$i]['regex_filter']) || strlen($schema[$i]['regex_filter']) != 0)
{
$validators[] = array(
'name' => 'regex',
'options' => array(
'pattern' => $schema[$i]['regex_filter'],
'messages' => array(
\Zend\Validator\Regex::INVALID => $schema[$i]['regex_invalid'],
\Zend\Validator\Regex::NOT_MATCH => $schema[$i]['regex_not_match'],
\Zend\Validator\Regex::ERROROUS => $schema[$i]['regex_errorus'],
)
)
);
}
//only add the validators if theres something in there
if(!empty($validators))
{
$form_options['validators'] = $validators;
}
$form->add($form_options);
}
//return our form object
return $form;
The block of code behaves the way I expect it, the output of $form_option after it's performed the above code looks like this:-
Array
(
[name] => username
[type] => Text
[required] => 1
[filters] => Array
(
[name] => StripTags
)
[validators] => Array
(
[0] => Array
(
[name] => StringLength
[options] => Array
(
[encoding] => UTF-8
[min] => 3
[max] => 50
)
)
[1] => Array
(
[name] => regex
[options] => Array
(
[pattern] => /^[a-zA-Z0-9_]{3,50}$/
[messages] => Array
(
[regexInvalid] => L_REGEX_INVALID
[regexNotMatch] => L_REGEX_USERNAME
[regexErrorous] => L_REGEX_ERRORUS
)
)
)
)
)
When I came to test it, it ignores the StringLength & Regex validators entirely, and only pay attention to the required validator for the last form element.
Anyone have any idea what's gone wrong?

Resources