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 ;
I have a controller with an action method:
namespace frontend\controllers;
class EmployeeController extends FrontController
{
/**
* Deletes an existing Employee status.
* #param integer $id
* #return mixed
*/
public function actionDeleteStatus($status_id)
{
error_log("actionDeleteStatus " . $status_id);
return $this->redirect(['update']);
}
}
In update form, I have a detail GridView, in which I want to add a "delete" link with an URL for this method as a GET request.
I try to get the URL with this: Url::toRoute(['employee/deleteStatus','status_id' => $model->status_id]) which gives me an url like /employee/deleteStatus?status_id=4 and throws a 404, here is the detailed code:
<div class="col-xs-12">
<?php
echo Html::label(Yii::t('app', 'Employee status history'));
echo GridView::widget([
'summary' => '',
'options' => [
'id' => 'status-history',
],
'emptyText' => '',
'export' => false,
'dataProvider' => $statusHistory,
'columns' => [
[...],
[
'class' => 'kartik\grid\DataColumn',
'attribute' => 'status_id',
'headerOptions' => [ 'class' => 'kv-grid-hide' ],
'contentOptions' => [ 'class' => 'kv-grid-hide' ]
],
[
'class' => 'yii\grid\ActionColumn',
'urlCreator' => function($action, $model, $key, $index) {
return Url::toRoute(['employee/deleteStatus','status_id' => $model->status_id]);
},
'template' => '{delete}',
'contentOptions' => ['class' => 'column-action'],
'buttons' => [
'delete' => function ($url, $model, $key) {
if (Yii::$app->user->can('globalDAF')) {
$options = [
'title' => Yii::t('app', 'Delete'),
'aria-label' => Yii::t('app', 'Delete'),
'data-confirm' => Yii::t('app', 'Sure to delete status?'),
'data-method' => 'post',
'data-pjax' => '0',
'class' => 'btn-llyc'
];
return Html::a('<span class="glyphicon glyphicon-remove"></span>', $url, $options);
} else {
return;
}
}
]
]
],
'hover' => true,
'responsiveWrap' => false
]);
?>
</div>
Is the url generation wrong? Why am I getting a 404?
Thanks.
For example, index becomes actionIndex, and hello-world becomes
actionHelloWorld.
Note: The names of the action methods are case-sensitive. If you have
a method named ActionIndex, it will not be considered as an action
method, and as a result, the request for the index action will result
in an exception. Also note that action methods must be public. A
private or protected method does NOT define an inline action.
Link
Url::toRoute(['employee/delete-status','status_id' => $model->status_id])
Or in config file:
'urlManager' => [
'class' => 'yii\web\UrlManager',
#code ..
'rules' => [
'employee/deleteStatus' => 'employee/delete-status',
],
],
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());
}
}
I have a form in ZF2 with the following element being added:
$this->add(array(
'name' => 'animals',
'type' => 'radio',
'attributes' => array(
'id' => 'animals',
'class' => 'form-control',
),
'options' => array(
'label' => 'Favourite animal',
'options' => array(
'cat' => 'Cat',
'dog' => 'Dog',
'fish' => 'Fish',
),
),
));
And in my view script I have the folloing line:
<?php echo $this->formrow($form->get('animals')); ?>
Which is generating the following html:
<fieldset>
<legend>Favourite Animal</legend>
<label><input type="radio" name="animals" id="animals" class="form-control input-error" value="cat">Cat</label>
<label><input type="radio" name="animals" class="form-control input-error" value="dog">Dog</label>
<label><input type="radio" name="animals" class="form-control input-error" value="fish">Fish</label>
</fieldset>
How do I add a class to the fieldset?
I have tried adding the following to the options array, the attributes array, and as an option to the main array but it is not adding the class to the fieldset:
'fieldset_attributes' => array(
'class' => 'form-group',
),
[edit]
Looking into the code (\Zend\Form\View\Helper\FormRow::render) I've found this:
...
// Multicheckbox elements have to be handled differently as the HTML standard does not allow nested
// labels. The semantic way is to group them inside a fieldset
if ($type === 'multi_checkbox' || $type === 'radio' || $element instanceof MonthSelect ) {
$markup = sprintf('<fieldset><legend>%s</legend>%s</fieldset>', $label, $elementString);
}
...
Which means the only way to add a class to the fieldset (or legend if you wanted) is to extend the view helper.
I followed the answer as posted here (https://stackoverflow.com/a/27273068/351785).
From the answer (modified to suit my requirements):
Create the Application\Form\View\Helper\FormRow.php helper class like
below:
<?php
/**
* Extend zend form view helper formrow to allow class to be added to fieldset / legend
*/
namespace Application\Form\View\Helper;
use Zend\Form\View\Helper\FormRow as ZendFormRow;
class FormRow extends ZendFormRow
{
/**
* Utility form helper that renders a label (if it exists), an element and errors
*
* #param ElementInterface $element
* #throws \Zend\Form\Exception\DomainException
* #return string
*/
public function render(\Zend\Form\ElementInterface $element)
{
//... other code here
// Multicheckbox elements have to be handled differently as the HTML standard does not allow nested
// labels. The semantic way is to group them inside a fieldset
if ($type === 'multi_checkbox'
|| $type === 'radio'
|| $element instanceof MonthSelect
) {
$fieldset_class = $legend_class = '';
if($class = $element->getOption('fieldset_class')) {
$fieldset_class = sprintf(' class="%s"', $class);
}
if($class = $element->getOption('legend_class')) {
$legend_class = sprintf(' class="%s"', $class);
}
$markup = sprintf(
'<fieldset%s><legend%s>%s</legend>%s</fieldset>',
$fieldset_class,
$legend_class,
$label,
$elementString);
}
//... other code here
return $markup;
}
}
And override the factory in the onBootstrap() method of the Module.php
file like below:
namespace Application;
use Zend\Mvc\MvcEvent;
use Zend\View\HelperPluginManager;
class Module
{
/**
* On bootstrap for application module.
*
* #param MvcEvent $event
* #return void
*/
public function onBootstrap(MvcEvent $event)
{
$services = $event->getApplication()->getServiceManager();
// The magic happens here
$services->get('ViewHelperManager')->setFactory('formrow', function (HelperPluginManager $manager) {
return new \Application\Form\View\Helper\FormRow();
});
}
}
And add the classes as such:
$this->add(array(
'name' => 'animals',
'type' => 'radio',
'attributes' => array(
'id' => 'animals',
'class' => 'form-control',
),
'options' => array(
'label' => 'Favourite animal',
'fieldset_class' => 'form-group', //<== this
'legend_class' => 'form-legend', //<== and this
'options' => array(
'cat' => 'Cat',
'dog' => 'Dog',
'fish' => 'Fish',
),
),
));
I have route.php like below :
Route::get('/edit/{num}', [
'as' => 'department.edit',
'middleware' => ['admin'],
'uses' => 'DepartmentsController#edit'
]);
Route::post('/update/{num}', [
'as' => 'department.update',
'middleware' => ['admin'],
'uses' => 'DepartmentsController#update'
]);
And edit.blade.php as below :
{!! Form::model($department, array('route' => ['department.update', Crypt::encrypt($department->id)], 'id' => 'department_update', 'class' => 'form-horizontal row-border')) !!}
#include('admin.departments._form')
{!! Form::label('', '', array('class' => 'col-md-2 control-label')) !!}
{!! Form:: submit('Update', ['class' => 'btn btn-success']) !!}
{!!form::close()!!}
And the DepartmentsController.php update() as :
public function update($id, Request $request) {
$id = Crypt::decrypt($id);
dd($_POST);
}
The above showing the POST variables :
array:3 [▼
"_token" => "UI6tBMuJlwmGZuaeB9ilJq6v0wUMOgKRlEY4eY0I"
"name" => "Material Management"
"department_code" => "MMD"
]
But if I try to output dd($request), it throws error
ReflectionException in AbstractCloner.php line 245: Class 1 does not
exist
Whats wrong ? Where I have made the mistake
Try this way, move your $request to 1st params.
public function update(Request $request, $id) {
$id = Crypt::decrypt($id);
dd($request->all());
dd($_POST);
}