Implementing flash messages in Yii framework - php

This is my function from my controller :
public function actionUser(){
Yii::app()->user->setFlash('success', "Data1 saved!");
....
}
In the view If I write this :
<?php echo Yii::app()->user->getFlash('success'); ?>
it works, BUT I want to appear somewhere above the content and then automatically fade out after a few second. I tried this from here
<?php
Yii::app()->clientScript->registerScript(
'myHideEffect',
'$(".info").animate({opacity: 1.0}, 3000).fadeOut("slow");',
CClientScript::POS_READY
);
?>
But i don't understand who is myHideEffect and the class .info ? Can someone give me an example ? or a link to a demo?
thanks .

Below there are two implementation for the flash message, We can show messages using toastr notification or the normal bootstrap flash messages implementation.
If you want display messages as toastr notification have this line of code your controller action.
YII::app()->user->setFlash('toastr.error', 'An Error occured when saving');
If you want to use the normal bootstrap flash message use instead.
YII::app()->user->setFlash('alert alert-danger', 'An Error occured.');
For this to work you have to handle the flash messages on your main view layout as below. Most likely just before <?php echo $content; ?>
/** Takes care of the flashmessages **/
$flashMessages = Yii::app()->user->getFlashes();
if ($flashMessages) {
foreach ($flashMessages as $key => $message) {
$pattern = '/\s/';
$match = preg_match($pattern, $key);/* This checks the type of error message to use if the error $key is just one word then use toastr notification */
if ($match == 0) {
Yii::app()->clientScript->registerScript(
'myNotifyEffect', $key . '("' . $message . '");', CClientScript::POS_READY
);
} elseif ($match > 0) {
if ($key != 'alert alert') {
Yii::app()->clientScript->registerScript(
'myHideEffect', '$(".' . $key . '").animate({opacity: 1.0}, 5000).fadeOut("slow");', CClientScript::POS_READY
);
echo '<div class= "' . $key . ' alert-bold-border square fade in alert-dismissable">' . '<button class="close" data-dismiss="alert" type="button">×</button>' . $message . "</div>\n";
} else {
echo '<div class="' . $key . ' alert-bold-border square fade in alert-dismissable">' . '<button class="close" data-dismiss="alert" type="button">×</button>' . $message . "</div>\n";
}
}
}
}

This is a jquery based question, not yii based. However try this:
<?php if(Yii::app()->user->hasFlash("success")): ?>
<div id="message">
<?php echo Yii::app()->user->getFlash('success'); ?>
</div>
<?php endif; ?>
...
<script>
$(document).ready(function() {
setTimeout(function() {
$('#message').fadeOut('slow');
}, 3000);
});
</script>

Related

How can I call a function action anywhere on a form?

I have a function that shows the uploaded avatar and remove button in case you want to delete the avatar. Everything works correctly. My problem is that the displayed avatar and remove button are merged together, if I want to move the remove button somewhere else I can't do it.
So I'm looking for a way to call the remove button wherever I want. I was thinking of js solutions to change the html structure as a last hope and solution, but I don't want to do that.
Anyone have any ideas on how I could move the remove button elsewhere? The function is located in functions.php, the destination I should move the button to is the form-edit-account.php template which I customized to my needs.
The line i want to move is this:
echo '<a href=' . wc_get_account_endpoint_url('impostazioni') . '?rm_profile_image_id=' . $attachment_id . '> ' . __('Remove') . ' </a>';
This is a complete function:
// Display / Remove Avatar
function action_woocommerce_edit_account_form($size) {
// Get current user id
$user_id = get_current_user_id();
// Get attachment id
$attachment_id = get_user_meta($user_id, 'image', true);
// True
if ($attachment_id) {
$original_image_url = wp_get_attachment_url($attachment_id);
// Display Image instead of URL
echo wp_get_attachment_image($attachment_id, $size = array('150', '150')); // Invece dell'array size, stava 'full' come parametro.
if (isset($_GET['rm_profile_image_id'])) {
if ($attachment_id == $_GET['rm_profile_image_id']) {
wp_delete_attachment($attachment_id);
//delete_user_meta($user_id, 'image');
if (delete_user_meta($user_id, 'image')) {
wp_delete_attachment($attachment_id);
}
?><script>window.location='<?php echo wc_get_account_endpoint_url('impostazioni') ?>';</script><?php
exit();
}
} else {
echo '<a href=' . wc_get_account_endpoint_url('impostazioni') . '?rm_profile_image_id=' . $attachment_id . '> ' . __('Remove') . ' </a>';
}
}
} add_action( 'woocommerce_edit_account_form_start', 'action_woocommerce_edit_account_form' );
Ok, it's weird but it works, I put the function directly inside the form. It's not a very "clean" solution, but it's working for me. If anyone thinks I am doing something wrong I appreciate any suggestions and corrections.
<form name="Form" class="mts-edit-account" action="" method="post" <?php do_action( 'woocommerce_edit_account_form_tag' );?> >
<!-- Avatar Remove button -->
<div class="global_container avatar">
<?php
if (isset($_GET['rm_profile_image_id'])) {
if ($attachment_id == $_GET['rm_profile_image_id']) {
wp_delete_attachment($attachment_id);
//delete_user_meta($user_id, 'image');
if (delete_user_meta($user_id, 'image')) {
wp_delete_attachment($attachment_id);
}
?><script>window.location='<?php echo wc_get_account_endpoint_url('impostazioni') ?>';</script><?php
exit();
}
} else {
echo '<a href=' . wc_get_account_endpoint_url('impostazioni') . '?rm_profile_image_id=' . $attachment_id . '> ' . __('Remove') . ' </a>';
} ?>
</div>
//Other fields........
</form>

Login Redirect PHP with Special Function

I have the following function set up in my includes and class file:
function makeMessage($message, $href, $onclick = '', $redirect = '', $linktext = 'Click here to continue') {
echo "<center>";
echo "<strong>" . $message . "</strong><br>" . $linktext . "";
if (! empty ( $redirect ))
echo "<br><meta http-equiv=\"refresh\" content=\"" . $redirect . "\"><strong>You should be redirected within a few seconds...</strong>
<br><br>Or let's check out now!";
echo "</center>";
}
However, on my register and login, add to order all uses this function, but I'm unsure what broke. Here's how I'm using it:
if ($post ['price_id'] == 0) {
$WALM->makeMessage ( 'You are now logged in!', 'order_now.php', '', 'order_now.php' );
} else {
}
The problem is, that it's not working with the meta refresh, does anyone have any help here to change this about and to what?
tags should be placed within the section. Maybe it's the problem?
You could try a JS redirect as follow:
function makeMessage($message, $href, $onclick = '', $redirect = '', $linktext = 'Click here to continue') {
echo "<center>";
echo "<strong>$message</strong><br/>$linktext";
if (!empty ($redirect))
echo "<br>
<script type=\"text/javascript\">
window.location = \"$redirect\"
</script>
<strong>You should be redirected within a few seconds...</strong>
<br><br>Or let's check out now!";
echo "</center>";
}
EDIT
You can not send headers considering that the redirect is not to the top of the page. If you want to delay the redirect, you can use the setTimeout() JS function
Use header() instead of <meta>
function makeMessage($message, $href, $onclick = '', $redirect = '', $linktext = 'Click here to continue') {
echo "<center>";
echo "<strong>" . $message . "</strong><br>" . $linktext . "";
if (! empty ( $redirect )) {
header("refresh:5;url=$redirect");
echo "<br><strong>You should be redirected within a few seconds...</strong>
<br><br>Or let's check out now!";
}
echo "</center>";
}

Avoiding line breaks in HTML output of PHP

Here I have my print function:
<?php
// little helper function to print the results
function printTag($tags) {
foreach($tags as $t) {
echo '<span class="' . $t['tag'] . '">';
echo $t['token'] . "/" . $t['tag'];
echo '</span>';
echo " ";
}
}
$tagger = new PosTagger('lexicon.txt');
?>
And here is what I'm outputting from an HTML form:
<?php
if($_POST['submitbutton'] == "Submit") {
//Check whether the form has been submitted
$tags = $tagger->tag($_POST['texttotag']);
printTag($tags);
}
?>
My problem is, the output in the browser results in strange line breaks in the middle of some of my <span> like so:
<span class="VB">Enter/VB</span> <span class="PRP$">your/PRP$</span> <span class="NN
">text/NN
</span> <span class="TO">to/TO</span> <span class="NN">tag/NN</span> <span class="RB
">here/RB
</span>
This means my CSS definitions don't apply to the "interrupted" spans. Any idea why this is happening and how I can stop it? I've had a good look around and haven't been able to find cause/solution. Thanks.
It seems that your $t['tag'] variable includes a line-break.
You can get rid of that using trim($t['tag']) instead.
It appears that the $t['tag'] in printTag function contains line break character. You can use str_replace function to remove these characters like:
function printTag($tags) {
foreach($tags as $t) {
echo '<span class="' . $t['tag'] . '">';
$ttag = str_replace('\n','',$t['tag']);
$ttag = str_replace('\r','',$ttag);
echo $t['token'] . "/" . $ttag;
echo '</span>';
echo " ";
}
}

Replace content of a div with an external php file in Laravel 3

I have an unordered list of movies being displayed from the Rotten Tomatoes API in a page called browse (using Laravel Framework). I am trying to use AJAX to load content into a div from a separate file that I have setup as a route called movie when the user clicks on the anchor.
In my routes file I have this:
Route::get('browse', array('as'=>'browse', 'uses'=>'browse#index'));
Route::get('movie', array('as'=>'movie', 'uses'=>'browse#movie'));
Browse View located at /application/views/browse/index.blade.php
$movies = $search_results->movies;
echo '<div id="browse">';
echo '<ul class="movieResults">';
foreach ($movies as $movie) {
echo '<div class="movieCard">';
echo '<li><img src="'. $movie->posters->detailed .'"</li>';
echo '<li class="movieCardInfo">' . $movie->title . '</li>'; // HERE'S WHERE I HAVE THE PROBLEM
echo '</div>';
}
echo '</ul>';
echo '</div>';
Movie View located at /application/views/browse/movie.blade.php. I have dummy text for now
echo '<div class="details">';
echo 'test';
echo '';
Browse Controller
public $restful = true;
public function get_index()
{
return View::make('browse.index')
->with('title', 'Browse Movies');
}
}
Javascript File
$(function() {
$('.movie').click(function() {
$('.details').load(this.href);
return false;
});
});
The project can be found here
Seems like your using the wrong "this"-operator. Should be "$(this)" if it's is a jQuery scripts? (The JavaScript part...)
Also: Ur telling it to add the result from ".load()" into the ".details", but I can't see that you have such a field in your html code?
EDIT
Change the following in /application/views/browse/index.blade.php:
echo '<li class="movieCardInfo">' . $movie->title . '</li>';
echo '<li class="movieCardInfo">' . $movie->title . '<div class="details"></div></li>';
And remove the "div.details" from the response, so the response only returns the text you want in your details.
Then, in the the JavaScript:
$(function() {
$('.movie').click(function() {
$('.details').load($(this).href);
return false;
});
});

on click change questions displayed

I have a page that has a list of items. On the bottom of the page is a "view more" button. When someone clicks this button, the page needs to add more items. The var is $displayedquestions, and the page is coded right now to refresh when the "view more" button is clicked, but we'd like to have it do it live. How can this be done?
Here is code:
<?php
include "db_connect.php";
db_connect();
function tags($tags)
{
$tagarray=explode(",",$tags);
$i=0;
$finished='false';
while($finished=='false') {
if (empty($tagarray[$i])=='true') {
$finished='true';
} else {
$taglist = $taglist . '<a class="commonTagNames" href="">' . $tagarray[$i] . '</a> ';
$i++;
}
}
return $taglist;
}
function formattime($timesince)
{
$strsince=number_format($timesince,0,'','');
$nodecimals=intval($strsince);
if ($nodecimals<1){
return "Less than a minute ago";
} elseif ($nodecimals>=1&&$nodecimals<60) {
return $nodecimals . " min ago";
} elseif ($nodecimals>60&&$nodecimals<1440){
$hourssince=$nodecimals/60;
$hoursnodecimals=number_format($hourssince,0);
return $hoursnodecimals . " hours ago";
} elseif ($nodecimals>1440){
$dayssince=$nodecimals/1440;
$daysnodecimals=number_format($dayssince,0);
return $daysnodecimals . " days ago";
}
}
$submitbutton=$_REQUEST['viewmore'];
$numquestions=intval($_REQUEST['questions']);
if($numquestions!=0) {
$displayedquestions=$numquestions;
} else {
$displayedquestions=10;
}
$sql="SELECT * FROM `Questions` ORDER BY `Questions`.`ID` DESC LIMIT 0, " . $displayedquestions;
$questions=mysql_query($sql);
while($row = mysql_fetch_array($questions))
{
$id = $row['ID'];
$user = $row['userAsking'];
$question = $row['question'];
$tags = $row['tags'];
$timestamp = $row['timestamp'];
$time=strtotime($timestamp);
$secondssince=(date(U)-$time)/60;
$timesince=formattime($secondssince);
$responses=mysql_query("SELECT * FROM `answersToQuestions` WHERE `idOfQuestion`= '$id'");
$comments=mysql_num_rows($responses);
$likes=mysql_query("SELECT * FROM `likesOfQuestions` WHERE `idOfQuestion`= '$id'");
$numlikes=mysql_num_rows($likes);
$userprofileq = mysql_query("SELECT `ID`,`avatar` FROM `Users` WHERE `username` = '$user'");
$userprofileresult = mysql_fetch_row($userprofileq);
$linktoprofile = $userprofileresult[0];
$avatar = $userprofileresult[1];
$taglist=tags($tags);
echo "</li>";
echo '<li class="questionsList" onclick="showUser(' . $id . ')">
<div id="questionPadding">
<img class="askerImage" width=50 height=50 src="../Images/userimages/' . $avatar . '.png"/>
<div class="questionFirstRow"><h1 class="questionTitle">' . $question . '</h1></div>
<span class="midRow">
<span class="askerSpan"><a class="askerName" href="">'. $user .'</a></span>
</span>
<span class="bottomRow">
<img src="../Images/comment.png"/>
<span class="comments">' . $comments . '</span>
<img src="../Images/likes.png"/>
<span class="likes">' . $numlikes . '</span>
' . $timesince . '
</span>
</div>
</li>';
}
?>
<center><img class="moreQuestions" src="../Images/viewMoreBar.png" alt="More" /></center>
Without doing a lot of work you can add ajax to this. Use this function:
First, (I am assuming you are including the code above into another file) create a container around it. Ex:
<div id='container'>...</div>
Second, add this javascript to the page that includes the code you have above:
<script type="text/javascript">
$(function(){
$("#container img.moreQuestions").parent().live('click', (function (e) {
e.preventDefault();
$("#container").load($(this).attr("href"));
});
});
});
</script>
This will load into #container the script you already have without refreshing the rest of the page.
Note the selector for the More link (slash button) in my example is $("#container img.moreQuestions").parent() because you don't have a class or id on it. You should give a class or id to the More link and use that for the selector.
like #diEcho mentioned, jQuery would be a great help: You could easily refresh your list of items by ajax (retrieving the complete list from a php file for example) as well as update your DOM elements with newly added values. Give it a try.
In addition you should think about getting you initial items by ajax as well. Data logic /display /UI functionality were seperated cleanly this way.

Categories