PHP - unset function unsets my var before my code - php

I would like to clear my session vqriqble "flash' using the unset function but now I can't print my flash message because the unset function is called before my previous code.
It is called in my header template : header.php wich is called in every page at the beginning of the code.
This is the code :
<?php if(isset($_SESSION['flash'])): ?>
<?php foreach($_SESSION['flash'] as $type => $message): ?>
<div class="alert alert-<?= $type; ?> bk-fullwidth-alert">
<p><?= $message; ?></p>
</div>
<?php endforeach; ?>
<?php unset($_SESSION['flash']); ?>
<?php endif; ?>
Thank you guys for your help !

Try this. The problem is that unset() was inside the loop, so the variable was being unset-ed on the first loop execution.
<?php if(isset($_SESSION['flash'])): ?>
<?php foreach($_SESSION['flash'] as $type => $message): ?>
<div class="alert alert-<?= $type; ?> bk-fullwidth-alert">
<p><?= $message; ?></p>
</div>
<?php endforeach; ?>
<?php unset($_SESSION['flash']); ?>
<?php endif; ?>
Edit: try this one
<?php
if(isset($_SESSION['flash'])) {
$flash = $_SESSION['flash'];
unset($_SESSION['flash']);
foreach($flash as $type => $message) {
?>
<div class="alert alert-<?=$type?> bk-fullwidth-alert">
<p><?=$message?></p>
</div>
<?php
}
}
?>

Related

Hide / show the part of code using php, if the value contains the letters

I have a problem with this scenario. There is a certain field (textarea) - $ COMMENTS. If the information in the $COMMENTS starts with a number (the first is a number and then any letter) - the script works fine (hide / show "some HTML and PHP code"), but if the $COMMENTS starts with the letter - the code does not work at all. Please tell me what is my mistake. I suffer already the 5th day.
Here is the script code, unfortunately it did not work correctly:
<?php $comments=$hm->Zb('rs:def:comments');
if ($comments!=0): ?>
<div class="txt"><?php echo $hm->Zb('rs:def:comments'); ?></div>
<?php else : ?>
<div class="sorry">Sorry, there is no comments</div>
<?php endif; ?>
also didn't work like this:
<?php $comments=$hm->Zb('rs:def:comments');
if ($comments!=""): ?>
<div class="txt"><?php echo $hm->Zb('rs:def:comments'); ?></div>
<?php else : ?>
<div class="sorry">Sorry, there is no comments</div>
<?php endif; ?>
Thank you all in advance for your help.
use isset() with if()
<?php $comments=$hm->Zb('rs:def:comments');
if (isset($comments)): ?>
<div class="txt"><?php echo $hm->Zb('rs:def:comments'); ?></div>
<?php else : ?>
<div class="sorry">Sorry, there is no comments</div>
<?php endif; ?>
EDIT
Please try below code.
<?php $comments=$hm->Zb('rs:def:comments');
echo $comments; //for debugging to ensure $comments have value.
if ($comments){ ?>
<div class="txt"><?php echo $hm->Zb('rs:def:comments'); ?></div>
<?php } else { ?>
<div class="sorry">Sorry, there is no comments</div>
<?php } ?>
http://php.net/manual/en/function.isset.php
try it : empty()
<?php $comments=$hm->Zb('rs:def:comments');
if (!empty($comments)): ?>
<div class="txt"><?php echo $hm->Zb('rs:def:comments'); ?></div>
<?php else : ?>
<div class="sorry">Sorry, there is no comments</div>
<?php endif; ?>

PHP: how can I add a specific title to my flash message?

I'm working on a flash message with PHP, but I would like to have a specific title for each of my flash message. My container for the flash message is set in my header.php so I can use this system everywhere on my site:
<?php if(isset($_SESSION["flash-message"])): ?>
<?php foreach($_SESSION["flash-message"] as $type => $message): ?>
<div class="alert alert-<?= $type; ?>">
<p><?= $message; ?></p>
</div>
<?php endforeach; ?>
<?php endif; ?>
To execute it, I use this:
$_SESSION["flash-message"]["success"] = "Test";
So, I have that:
Now, I would like to have a title, you know? Something like that:
$_SESSION["flash-message"]["title" = "The title"]["success"] = "The message"
Just something like that. I want the title above the message.
Short answer: use an array or object to store your message with corresponding title.
$_SESSION["flash-message"]["success"] = array("Title", "The Message");
And your code will be like following:
<?php if(isset($_SESSION["flash-message"])): ?>
<?php foreach($_SESSION["flash-message"] as $type => $message): ?>
<div class="alert alert-<?= $type; ?>">
<h2><?= $message[0]; ?></h2>
<p><?= $message[1]; ?></p>
</div>
<?php endforeach; ?>
<?php endif; ?>
EDIT:
And what happens if you have more than one success message? Your current code doesn't support multiple "same type" messages. It should be:
$_SESSION["flash-message"]["success"][] = array("Title", "The Message");
to store multiple "same-type" messages.
EDIT-2:
You can also use object approach - more readable. Also contains multiple message ability I mentioned above.
<?php
$message = new stdClass();
$message->title = "Title";
$message->message = "The Message";
$_SESSION["flash-message"]["success"][] = $message;
?>
<?php if(isset($_SESSION["flash-message"])): ?>
<?php foreach($_SESSION["flash-message"] as $type): ?>
<?php foreach ($type as $message): ?>
<div class="alert alert-<?= $type; ?>">
<h2><?= $message->title; ?></h2>
<p><?= $message->message; ?></p>
</div>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif; ?>
$_SESSION["flash-message"] should be an array of messages, and a message should have an event_type, a title and a content.
You can model messages in many forms, with classes or associative arrays. See this example message modeled with an associative array:
$a_message = [
"event_type" => "success",
"title" => "The title"
"content" => "The message"
];
This way, you could implement your foreach loop like this:
<?php if(isset($_SESSION["flash-message"])): ?>
<?php foreach($_SESSION["flash-message"] as $message): ?>
<div class="alert alert-<?= $message["event_type"]; ?>">
<h1><?= $message["title"]; ?></p>
<p><?= $message["content"]; ?></p>
</div>
<?php endforeach; ?>
<?php endif; ?>

This php if else code on my website is not working [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
<?php if (get_the_author_meta('description')) { ?>
<?php
$author_ID = get_the_author_meta('ID');
$username = get_the_author_meta('display_name', $author_ID); ?>
<div class="mm-author-box">
<figure class="mm-author-box-avatar">
<?php echo get_avatar($author_ID, 70); ?>
</figure>
<?php if ($author_ID === 4) { ?>
<div class="mm-author-name">
<?php echo $username; ?>
</div>
<div class="mm-author-bio">
<?php echo get_the_author_meta('description'); ?>
</div>
</div>
<?php } ?>
<?php else { ?>
<?php if ($author_ID === 9) { ?>
<div class="mm-author-name">
<?php echo $username; ?>
</div>
<div class="mm-author-bio">
<?php echo get_the_author_meta('description'); ?>
</div>
</div>
<?php } ?>
<?php } ?>
It is a code to display author name and hyper link it.
From the first if statement if author has a description then go inside
Second if statement: if authors ID is 4 then execute the code below if not then
Else, there is one extra div inside the else statement which is for <div class="mm-author-box"> which is outside the if statement.
The problem is that when I put this code it breaks the page.. Only the header of the website loads and the content below it doesn't because i have placed this code in the php file which is a template for the page content.
I think there is some syntax problem coz I used the code without else statement and it worked.
You missed to close a curly bracket in the end. Add below line as a last line and try :
<?php } ?>
I don't know how strict that template engine is, but this could be the problem;
<div class="mm-author-bio">
<?php echo get_the_author_meta('description'); ?>
</div>
</div>
<?php } ?>
You're closing the div inside the if which was started outside the div. So , place that last </div> below the <?php } ?> and see if that helps
<?php if (get_the_author_meta('description')) {
$author_ID = get_the_author_meta('ID');
$username = get_the_author_meta('display_name', $author_ID); ?>
<div class="mm-author-box">
<figure class="mm-author-box-avatar">
<?php echo get_avatar($author_ID, 70); ?>
</figure>
<?php if ($author_ID === 4) { ?>
<div class="mm-author-name">
<?php echo $username; ?>
</div>
<div class="mm-author-bio">
<?php echo get_the_author_meta('description'); ?>
</div>
<?php } else if ($mh_author_ID === 9) { ?>
<div class="mm-author-name">
<?php echo $username; ?>
</div>
<div class="mm-author-bio">
<?php echo get_the_author_meta('description'); ?>
</div>
<?php } ?>
</div>
<?php } ?>
And as AnkiiG pointed out, you missed a closing tag, which I fixed without knowing while formatting my answer
Your if else structure is like this,
<?php if (get_the_author_meta('description')) { ?>
<?php if ($author_ID === 4) { ?>
<?php } ?>
<?php else { ?>
<?php if ($mh_author_ID === 9) { ?>
<?php } ?>
You're not closing the first if statement

Checking if a variable exists within foreach if statement

In the below code, when checking foreach(get_sub_field("items") as $x):
How do I check if $x['item_name']; is empty, do this...
<?php $food = 23; ?>
<?php while(has_sub_field("menu_items", $food)): ?>
<?php if(get_row_layout() == 'food_items'): ?>
<?php if (get_sub_field('category')){?>
<h2>
<?php the_sub_field('category');?>
</h2>
<?php } ?>
<div>
<?php if(get_sub_field("items")): ?>
<?php foreach(get_sub_field("items") as $x): ?>
<div> <?php echo $x['item_name']; ?> <?php echo $x['item_price']; ?>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
<?php endif; ?>
<?php endwhile; ?>
You can try this :
<?php if (empty($x['item_name'])) : ?>
<p>It's empty</p>
<?php endif; ?>
try empty()
<?php echo (!empty($x['item_name']) ? $x['item_name'] : 'do this'); ?>
or
if(!empty($x['item_name'])) {
echo $x['item_name'];
}
else {
// do your stuff
}

Yii: How to update multiple models using only 1 form 1 model and 1 action?

I have a model website and a model url.
Each url data is attached to a website data. A url is related to a website via a website_id.
On my web app, I need to check the data before accepting it.
I want to see on screen the entire data regarding a url data and I managed to do this.
Now, I also want to update the entire data that is listed on screen.
On screen I have the entire url data and website data, but when I try to save the data, the website data is empty.
My logic was to add to the url model a property: public $website;
And within the url model, a method aftersave:
protected function afterSave() {
$w = null;
$w = Website::model()->findByAttributes(array('id' => $this->website_id));
//echo '<pre>';
//print_r($w);
print_r($this->website);
$w->link = $this->website['link'];
$w->domain = $this->website['domain'];
$w->description = $this->website['description'];
$w->save(false);
die;
return parent::afterSave();
}
and here is the important code from the _form file:
<div class="row">
<?php echo $form->labelEx($model,'will_expire'); ?>
<?php echo $form->dropDownList($model,'will_expire',array(0=>'No',1=>'Yes')); ?>
<?php echo $form->error($model,'will_expire'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'link'); ?>
<?php echo $form->textField($model_website,'link'); ?>
<?php echo $form->error($model_website,'link'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'domain'); ?>
<?php echo $form->textField($model_website,'domain'); ?>
<?php echo $form->error($model_website,'domain'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'description'); ?>
<?php echo $form->textField($model_website,'description'); ?>
<?php echo $form->error($model_website,'description'); ?>
</div>
There are few questions:
Is the relation url and website being defined in the model such that $url->website of a existing url gives you valid website record?
You form shows, you are not using any website_id, means that you are creating a new website record for every URL, means $w = Website::model()->findByAttributes(array('id' => $this->website_id)); will always return NULL
I assume you have defined a relation of website within your URL model.
Suggested function from my understanding:
protected function afterSave() {
//data is already assigned by the caller
$w = null;
$w = Website::model()->findByAttributes(array('id' => $this->website_id));
if($w)
{
Yii::log("updating existing website data","info");
$this->website->save();
}
else
{
Yii::log("creating new website data","info");
$this->website->save();
$this->website_id = $this->website->website_id;
$this->update(array('website_id')); //save the relation
Yii::log("created new website {$this->website_id}","info");
}
return parent::afterSave();
}
It turned out to be small mistakes like w instead of W, object property instead of array;
Ok, so let me teach you how to do this;
I have 2 models: Url and Website.
Url model has a foreign key website_id and a relation to model Website;
Within the Url model I have a property called website and i declared it like: public $website = array();;
The data gets added thru a bookmarklet that uses a API so the data will be there when the admin comes to update/check it;
In the Url model i have a method afterSave:
protected function afterSave() {
$w = null;
$w = Website::model()->findByAttributes(array('id' => $this->website_id));
if($w)
{
$w->link = $this->website['link'];
$w->domain = $this->website['domain'];
$w->description = $this->website['description'];
$w->save();
}
return parent::afterSave();
}
where $this->website gets populated in the UrlController on actionUpdate like:
public function actionUpdate($id, $type = 'update') {
$model = $this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Url'])) {
$model->attributes = $_POST['Url'];
$model->website = $_POST['Website'];
if ($model->save())
if ($type == 'update')
$this->redirect(array('view', 'id' => $model->id));
else
$this->redirect(array('/admin/url/approvePublicLink'));
}
$model_website = Website::model()->findByAttributes(array('id'=>$model->website_id));
$this->render('update', array(
'model' => $model,
'model_website' => $model_website,
));
}
and gets passed to the afterSave method later;
this is the _update view:
<div style="padding:20px 20px;">
<h1>Update Url, Website, Keywords ...</h1>
<?php echo $this->renderPartial('_form', array(
'model'=>$model,
'model_website' => $model_website,
)); ?>
</div>
and this is the _form view that gets rendered partial:
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'url-form',
'enableAjaxValidation'=>false,
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'website_id'); ?>
<?php echo CHtml::link($model->relation_website->domain,$model->relation_website->domain,array('class'=>'avia','target'=>'_blank')); ?>
<?php echo $form->error($model,'website_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'link'); ?>
<?php echo $form->textField($model,'link',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'link'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'title'); ?>
<?php echo $form->textField($model,'title',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'description'); ?>
<?php echo $form->textField($model,'description',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'important'); ?>
<?php echo $form->dropDownList($model,'important',array(0=>'Normal',1=>'Important')); ?>
<?php echo $form->error($model,'important'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'views'); ?>
<?php echo $form->textField($model,'views'); ?>
<?php echo $form->error($model,'views'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'created'); ?>
<?php echo $model->created; ?>
<?php echo $form->error($model,'created'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'updated'); ?>
<?php echo $model->updated; ?>
<?php echo $form->error($model,'updated'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'will_expire'); ?>
<?php echo $form->dropDownList($model,'will_expire',array(0=>'No',1=>'Yes')); ?>
<?php echo $form->error($model,'will_expire'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'link'); ?>
<?php echo $form->textField($model_website,'link'); ?>
<?php echo $form->error($model_website,'link'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'domain'); ?>
<?php echo $form->textField($model_website,'domain'); ?>
<?php echo $form->error($model_website,'domain'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'description'); ?>
<?php echo $form->textField($model_website,'description'); ?>
<?php echo $form->error($model_website,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'status'); ?>
<?php echo $form->dropDownList($model,'status',array(-1=>'Banned',0=>'Normal',1=>'Active')); ?>
<?php echo $form->error($model,'status'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
I hope it helps.

Categories