CakePHP: Error message not showing Validate Fields - validation

I am new to CakePHP. I have two problem with the view.
There is line break between text field name and text field area. I have tried to pass 'div' => false but that didn't work. How can I remove line break and display both on same line?
I have added validation rule to this textfield but when I click save Error message doesn't show up. Do I need to do something else beside adding validates in my model?
Here is my view input.ctp
echo $this->Form->input('fileId', array(
'type'=>'text',
'style' => 'width: 200px; height: 15px'
));
echo $this->Form->end('Save Post');
Here is my model:
var $validate = array(
'fileId' => 'notEmpty',
'message' => 'Should not be empty'
);
Controller:
if ($this->request->is('post')) {
$data = $this->request->data;
if ($data) {
// saving the data
}
}

If you are not using save then you need to manually validate the data using validates. In such case you also need to set the data. For e.g. in your controller
$this->ModelName->set($data);
$this->Modelname->validates();

For validate your data, you should have something like this:
public $validate = array(
'fileId' => array(
'rule' => 'notEmpty',
'message' => 'Should not be empty'
)
);
And your Controller:
if ($this->request->is('post')) {
if ($this->Model->save($this->request->data)) {
// saved
}
}
If you can not save, the error will be shown near the corresponding field. Or you can customize your error using $this->Model->validationErrors array.
For the line break question, make sure that 200px does the automatic line break because of where these elements are positioned.

validation errors appear when validates() or save() was called.
setup your action completely.
If you're not using FormHelper::input, which outputs the field, label and error, you need to manually output the error as well using $this->Form->error('fileId').
And for the form try this:
add this to your css
label { float: left;
width: 150px;
display: block;
clear: none;
text-align: left;
vertical-align: middle;
padding-right: 0px;}
.xg {
display: block;
float:left;
}
echo $this->Form->input('fileId', array('div'=>'xg','type'=>'text', 'style' => 'width: 200px; height: 15px'));
echo $this->Form->end('Save Post');

you can customize your output by following method:
<tr>
<td><label>Username</label></td>
<td>
<?php echo $this->Form->input('username',array('label'=>false,'div'=>false,'error'=>false)); ?>
</td>
<td><?php echo $this->Form->error('username'); ?></td>
</tr>
This method will give you output in same line.

Related

Animated icon inside input

How can I add a font awsome animated icon ( like fa fa-reload fa-spin) inside an input using $this->form->input(code)
<div class="input-wrapper">
<input id="stuff">
<label id ="spin" for="stuff" class="fa fa-spinner fa-spin input-icon">
</label>
</div>
and for css
.input-icon{ position: relative; right: 20px; }
input{ padding-right: 20px; }
.input-wrapper{ position: relative; }
I don't know if what you're trying to do it's right from a css point of view
Don't even know if it is the right way to use fontAwesome (You're applying the fa classes to the label instead o using in a <i> as usually done)
So I'm just going to show you how to replicate your exact html using cakephp
if you want to do using just one command you have to leverage on templates. You can change the form templates just for one form, for your whole application or just for a single control.
In my exhample I'm changing the templates just for this control
echo $this->form->control(
'my_input_name',
[
'label' => [
'text' => '',
'id' => 'spin',
'class' => "fa fa-spinner fa-spin input-icon"
],
'templates' => [
'inputContainer' => '<div class="input-wrapper">{{content}}</div>',
'formGroup' => '{{input}}{{label}}',
]
]
)

yii2 Image to have a label below the image

In yii2 I am displaying images from the daabase and for the same images I have comments in the database table. I want the image description to be below the image, which i am not able to achieve.
My code.
<div class="margin-top-20">
<h5> <p class="details-edit"> <i class="fa fa-picture-o"></i> GHS Pictograms </p> </h5>
<div class="panel panel-default panel-edit">
<div class="panel-body">
<?php
$images = '';
$a = '';
// append all images
// var_dump($data->getPictogramPath()); exit();
foreach($model->getPictogramPath() as $name)
$images =$images.' '.Html::img(\Yii::$app->request->BaseUrl.'/web'.$name->pictogram_filepath,['alt'=>'','width'=>'100','height'=>'100', 'data-toggle'=>'tooltip','data-placement'=>'left','title' => $name->pictogram_comment ,'style'=>'cursor:default;']).Html::label($name->pictogram_comment,['class' => 'pictogram-label']);
$a = $a.Html::label($name->pictogram_comment);
echo ($images);
?>
</div>
</div>
</div>
My output is :
I am not able to get the label below the image.. Can anyone sugggest me what is the issue here?
Thank you..
You need to have a little change on your html structure. First of all need wrap each image and label in block, also need make a couple changes in your css files.
You code will look like this:
$images = '';
$a = '';
// Append all images
foreach($model->getPictogramPath() as $name) {
$images .= Html::beginTag('div', ['class' => 'img-and-label-wrapper']);
$images .= Html::img(\Yii::$app->request->BaseUrl. '/web' . $name->pictogram_filepath, ['alt' => '', 'width' => '100', 'height' => '100', 'data-toggle' => 'tooltip', 'data-placement' => 'left', 'title' => $name->pictogram_comment ,'style'=>'cursor:default;']);
$images .= Html::label($name->pictogram_comment,['class' => 'pictogram-label']);
$images .= Html::endTag('div');
}
echo $images;
Here styles that you need to add:
.img-and-label-wrapper {
display : inline-block;
}
.img-and-label-wrapper label{
display: block;
text-align: center;
}
Guess this will helpful for you

css inside gridview not showing after ajaxupdate

inside a gridview i have a css based inline graph. everything is working fine untill i filter something and the gridview gets updated. then css is not registering inside the grid anymore. anyone knows a solution? to be honest i don't even know what to try in this situation. css is not one of my strong points.
this is the element before ajaxupdate:
This is after the ajax update
.stat-block .stat-graph {
background: none repeat scroll 0 0 #FFFFFF;
border: 1px solid #D7D7D7;
border-radius: 3px;
margin-right: 10px;
padding: 10px 10px 8px;
text-align: center;
width: auto;
}
as far as i can see first time the grid is generated css generates a canvas tag like so
<canvas style="display: inline-block; width: 29px; height: 20px; vertical-align: top;" width="29" height="20"></canvas>
but after the ajax update and the refresh of the gridview that tag won't appear anymore.
i have tried to put the graph data inside the canvas tag whit no success.
here is the gridview code:
this->widget('zii.widgets.grid.CGridView', array(
'id' => 'cartuse-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'afterAjaxUpdate' => 'reinstallDatePicker',
'columns' => array(
array(
'id' => 'autoId',
'class' => 'CCheckBoxColumn',
'selectableRows' => '50',
),
// 'id',
array(
'name'=>'client',
'type'=>'raw',
'value'=>'client($data->client)',
'htmlOptions' => array(
'align'=>'center',
//'width'=>'35%'
)
here is the client function:
function client($client) {
...
return '<div class="stat-block" id="graph">
<ul>
<li class="stat-graph inlinebar" id="activitate-lunara">
'.$data.'
</li>
<li class="stat-count">
<span>'.$data['0'].'
</span>
</li>
<li class="stat-percent">
<span class="text-info stat-percent">'.$target.'</span>
</li>
</ul>
</div>';
}
Edit 1 :
as recomended in answer 1 i used the removeClass() and addClass() functions to refresh css after ajax update. nothing hapens, the canvas tag still won't appear.
i tryed to use replaceWith() and just insert the canvas tag that way but then it will brake the filtering.
here's the reinstallDatePicker function
<?php Yii::app()->clientScript->registerScript('re-install-date-picker', "
function reinstallDatePicker(id, data) {
$('#datepicker_min').datepicker({ dateFormat: 'yy-mm-dd',
showOtherMonths: true,
selectOtherMonths: true,
changeYear: true,
changeMonth: true,
});
$('#datepicker_max').datepicker({ dateFormat: 'yy-mm-dd',
showOtherMonths: true,
selectOtherMonths: true,
changeYear: true,
changeMonth: true,
});
$( \"#activitate-lunara\" ).removeClass( \"stat-graph inlinebar\" );
$( \"#graph\" ).removeClass( \"stat-block\" );
$( \"#graph\" ).addClass( \"stat-block\" );
$( \"#activitate-lunara\" ).addClass( \"stat-graph inlinebar\" );
}"); ?>
Edit 2:
i wasn't using renderPartial as column content. just a function that returned the content i wanted. after exhausting All posible ideeas i moved to renderpartial and with renderpartial + registering scripts / css in the partialview and removeclass / addclass everything is working fine now.
I have this issue sometimes as well.
First thing: If you're using partial views, include the CSS in the partial view as well.
If not, you will probably have to re-apply the style after each ajax update.
I see that you are using "afterAjaxUpdate"=>"reinstallDatePicker" so one way to fix your problem is to add that CSS to .stat-block .stat-graph inside that function. You can use jquery functions like css(), addClass() and many others.
But the important thing is that you style your elements after each ajax update. Since your function reinstallDatePicker is being called after each ajax update, you can just add some code to this function to do what you want (that is, re-style the elements).
i have tried everything i can think of without success. the only way i could get it to work was to store my filter data in my session and then afterajaxupdate force a reload. (not really recommended because if your query's are not optimized i guess it could slow down your page)
i'm just posting this here in case someone else has this problem and want to get it working before someone else finds a correct solution
so now in my controller i have this
public function actionAdmin()
{
$model=new Cartuse('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Cartuse']))
$_SESSION['filterData'][$this->id][$this->action->id] = $_GET['Cartuse'];
$model->attributes=$_SESSION['filterData'][$this->id][$this->action->id];
if (isset($_GET['pageSize'])) {
Yii::app()->user->setState('pageSize',(int)$_GET['pageSize']);
unset($_GET['pageSize']);
}
$this->render('admin',array(
'model'=>$model,
));
}
and in my gridview
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'cartuse-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'afterAjaxUpdate' => 'reinstallDatePicker',
'columns' => array(/*
.....
)
));
and the reinstall datepicker (for some reason if i put the location.reload () directly in the afterajaxupdate field my datepickers won't register (not even first time) and filtering stops working. so i put it in the reinstalldatepicker function. no problems till now.
<?php Yii::app()->clientScript->registerScript('re-install-date-picker', "
function reinstallDatePicker(id, data) {
location.reload();
$('#datepicker_min').datepicker({ dateFormat: 'yy-mm-dd',
showOtherMonths: true,
selectOtherMonths: true,
changeYear: true,
changeMonth: true,
});
$('#datepicker_max').datepicker({ dateFormat: 'yy-mm-dd',
showOtherMonths: true,
selectOtherMonths: true,
changeYear: true,
changeMonth: true,
});
$.datepicker.setDefaults($.datepicker.regional['ro']);
}
");
this is not really a solution, its jut a cheap workaround so if anyone has a solution i'll be waiting for it.

CodeIgniter anchor function without any string in value

My code right now:
<?php echo anchor('admin/delete_msg/'.$obj->id, 'DELETE MESSAGE', array('onclick' => 'return confirm(\'Are you sure?\');', 'class' => 'delete-button')); ?>
But Iwould liek to use something like:
<?php echo anchor('admin/delete_msg/'.$obj->id, '', array('onclick' => 'return confirm(\'Are you sure?\');', 'class' => 'delete-button')); ?>
So there is no "DELETE MESSAGE" text and I can use image instead.
But if I leave the single quotes empty the link will show up e.g. http://localhost/project
Any advice how to solve that within anchor function and not going via <a href="...?
You could use CSS to hide the text and pull in a background image:
.delete-button{
display: inline-block;
width: 80px; /* fits background-img width */
height: 40px; /* fits background-img height */
text-indent: -9999px;
background: url('path/to/image') top left no-repeat;
}
I have solved it using space like:
<?php echo anchor('admin/delete_msg/'.$obj->id, ' ', array('onclick' => 'return confirm(\'Are you sure?\');', 'class' => 'delete-button')); ?>
Don't use the anchor helper. Just pass $obj to the view(html.php)
<a rel="nofollow" onclick="return confirm()" class="btn btn-delete-icon" href="<?php echo site_url('admin/delete_msg/'.$obj->id.'')?>"> </a>

Automatically Generate and Email unique voucher code for every sale

I have been hunting around for a solution to this problem I am trying to resolve.
Here is the scenario:
I want to issue a single use voucher code for every purchase made between two specified dates. The voucher is to be redeemed between another two specified dates. The voucher must be single use only, but could potentially be given away if the original purchaser doesn't want/need it.
Each customer can be assigned any number of individual voucher codes - one to be issued per purchase.
The voucher code should be automatically generated and emailed to them with their order confirmation, so there is no manual work required.
Can someone help either with usable code for Magento 1.6.2, or point me towards a plugin that might do the job?
I have contacted MageStore about their offering to ask if it fits my needs, but thought I would ask the question here in case I can get an answer/solution faster, as they are not available at this time.
=== Final working solution ===
I found code in various places that each had bits that helped, but not one overall working solution for me. Eventually, I managed to hack this together into a module - here is the observer.php part of that module (the crux of the beast). I hope it helps someone!
Note - this code worked for ME in MY scenario. I cannot offer any support on this, and take no responsibility for it's use in your application - please make use of it as you see fit.
<?php
/**
* Our class name should follow the directory structure of
* our Observer.php model, starting from the namespace,
* replacing directory separators with underscores.
* i.e. app/code/local/SmashingMagazine/
* LogProductUpdate/Model/Observer.php
*/
class Robgt_AutoVoucher_Model_Observer
{
/**
* Magento passes a Varien_Event_Observer object as
* the first parameter of dispatched events.
*/
public function autoVoucher(Varien_Event_Observer $observer)
{
// Should we run this code at all?
// Between 17th at midnight and 24th at midday December 2012 ONLY
$from = strtotime('2012-12-17 00:00:01');
$to = strtotime('2012-12-24 11:59:59');
$now = time();
if($from <= $now && $to >= $now) {
//Get the Order ID
$order = $observer->getEvent()->getOrder();
$orderEntityId = $order->getId();
$orderid = $order->getIncrementId();
//$orderid = Mage::getSingleton('checkout/session')->getLastRealOrderId();
if(empty($orderid))
{
$orderid = '999999999';
}
// Grab the last 3 digits of the Order number for use in the voucher code
$last_orderNumberDigits = substr($orderid, -3, 3);;
// Create coupon code random part
$codeLength = 7;
$chars = "ABCDEFGHIJKLMNPQRSTUVWXYZ1234567890";
srand((double)microtime()*1000000);
$i = 0;
$code = '' ;
while ($i <= $codeLength)
{
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$code = $code . $tmp;
$i++;
}
$couponRandomCode = $code;
// Build coupon code
// Format is: MH[Last 3 Digits of Order number]-[5 Random digits]
$couponCode = 'MH'.$last_orderNumberDigits.'-'.$couponRandomCode;
$couponName = 'Xmas2012 - '.$couponCode;
// Build the coupon rule
$rule = Mage::getModel('salesrule/rule');
$rule->setName($couponName);
$rule->setDescription('Xmas 2012 Discount coupon');
$rule->setFromDate('2013-01-01'); // Jan 1st
$rule->setToDate('2013-01-31'); // Jan 31st
$rule->setCouponType(2);
$rule->setCouponCode($couponCode);
$rule->setUsesPerCoupon(1);
$rule->setUsesPerCustomer(1);
$rule->setCustomerGroupIds('0,1,3,4');
$rule->setIsActive(1);
$conditions = array(
"1" => array(
'type' => 'salesrule/rule_condition_combine',
'aggregator' => 'all',
'value' => 1,
'new_child' => false
),
"1--1" => array(
'type' => 'salesrule/rule_condition_product_found',
'value' => 1,
'aggregator' => 'all',
'new_child' => false
),
"1--1--1" => array(
'type' => 'salesrule/rule_condition_product',
'attribute' => 'category_ids',
'operator' => '!()',
'value' => '932,341,800,1116'
)
);
$actions = array(
"1" => array(
"type" => "salesrule/rule_condition_product",
"aggregator" => "all",
"value" => "1",
"new_child" => false
),
"1--1" => array(
"type" => "salesrule/rule_condition_product",
"attribute" => "category_ids",
'operator' => '!()',
'value' => '932,341,800,1116'
)
);
$rule->setData('conditions',$conditions);
$rule->setData("actions",$actions);
$rule->setStopRulesProcessing(1);
$rule->setIsAdvanced(1);
$rule->setProductIds('');
$rule->setSortOrder(0);
$rule->setSimpleAction('by_percent');
$rule->setDiscountAmount(10);
$rule->setDiscountStep(0);
$rule->setSimpleFreeShipping(0);
$rule->setTimesUsed(0);
$rule->setIsRss(0);
$rule->setWebsiteIds('1');
$rule->loadPost($rule->getData());
$rule->save();
// Email the details to Trev
$to = 'trevor.wallinger#gmail.com';
//$to = 'robgt.com#gmail.com';
$subject = 'New Xmas 2012 Voucher Code';
$message = '<body style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;">
<div style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;">
<table cellspacing="0" cellpadding="0" border="0" height="100%" width="100%">
<tr>
<td align="center" valign="top" style="padding:20px 0 20px 0">
<!-- [ header starts here] -->
<table bgcolor="FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
<tr>
<td valign="top">
<h1 style="font-size:22px; font-weight:normal; line-height:22px; margin:0 0 11px 0;">A new coupon code was generated, as follows:</h1>
<p style="font-size:12px; line-height:16px; margin:0 0 8px 0;"><strong>Order Number:</strong> '.$orderid.'</p>
<p style="font-size:12px; line-height:16px; margin:0 0 8px 0;"><strong>Coupon Code:</strong> '.$couponCode.'</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</body>
';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
try {
mail($to, $subject, $message, $headers);
$mailReport = 'Mail sent!';
}
catch(Exception $ex) {
$mailReport = "Mail failed to send!";
}
// Log the voucher code generated
// Saved to /var/log/coupons.log
Mage::log(
"Coupon created: {$couponCode} | Order ID: {$orderid} | Mail Report: {$mailReport}\n\r",
null,
'coupons.log'
);
} // End If Date check.
}
}

Resources