Shortcode with array of options and conditional display based on options - php

I have been looking for a solution and couldn't find.
I have created a shortcode that displays social link depends on type with folowing code:
function ns_social_buttons_dynamic($atts,$content,$tag) {
$facebookUrl = get_option('ns-company-facebook');
$messengerUrl = get_option('ns-company-messenger');
if (!empty($facebookUrl)) {
$fb = '<a class="btn-ns btn-ns-second m-1 bg-facebook" href="https://facebook.com/'.$facebookUrl.'" role="button" target="blank"><i class="fab fa-facebook-f"></i></a>';
};
if (!empty($messengerUrl)) {
$msngr = '<a class="btn-ns btn-ns-second m-1 bg-messenger" href="https://m.me/'.$messengerUrl.'" role="button" target="blank"><i class="fab fa-facebook-messenger"></i></a>';
}
$nsSocial = $fb . $msngr;
//get admin url
$addLink = get_site_url( $blog_id, 'wp-admin/', $scheme );
//default value of shortcodes shows all social buttons
$values = shortcode_atts(array(
'type' => 'all',
'output' => 'raw',
),$atts);
//social button based on type
$output = '';
if($values['type'] == 'all' and !empty($nsSocial)){
$output = $nsSocial;
}
else if($values['type'] == 'facebook' and !empty($facebookUrl)){
$output = $fb;
}
else if($values['type'] == 'messenger' and !empty($messengerUrl)){
$output = $msngr;
}
else {
$output = 'field is empty <a href=' . $addLink . 'admin.php?page=ns-settings' .' >add username</a>';
}
return $output;
}
add_shortcode( 'ns-social', 'ns_social_buttons_dynamic' );
This code works just fine e.g [ns-socia type='facebook'] will output the right button.
now what I need is if the shortcode like following [ns-socia type='facebook' output='raw'] to show only the url and not the button.
I tried following:
//social button based on type
$output = '';
if($values['type'] == 'all' and !empty($nsSocial)){
$output = $nsSocial;
}
else if($values['type'] == 'facebook' and $values['output'] == 'raw' and !empty($facebookUrl)){
$output = $facebookUrl;
}
else if($values['type'] == 'messenger' and $values['output'] == 'raw' and !empty($messengerUrl)){
$output = $messengerUrl;
}
else {
$output = 'field is empty <a href=' . $addLink . 'admin.php?page=ns-settings' .' >add username</a>';
}
return $output;
I am not sure i am doing it right with the conditional php conditional statements...

Related

how to add a column in yii gridview with each value having different button color

Thanks I really appreciate the help, but please I am trying to display a different button colour depending on the value of the status and I have tried different ways but it isn't working.
[
'label' => 'Status',
'format' => 'raw',
'value' => function ($model) {
if ($model->status = "Approved") {
$sta = "btn-success";
} elseif ($model->status = "Pending...") {
$sta = "btn-info";
} else {
$sta = "btn-danger";
}
$btn = ''.$model->status.'';
return $btn;
},
],
this one only see the first only displays "approved " for all the value and makes them all one colour..
I also did this
[
'label' => 'Status',
'format' => 'raw',
'value' => function ($model) {
foreach ($model->status as $status) {
if ($model->status = "Approved") {
$sta = "btn-success";
$btn = '<a href="' . Url::home() . 'site/index?id=' . $model->id .'"
data-toggle="tooltip" title="Status" data-placement="bottom" class="btn btn-sm
'.$sta.' ">'.$model->status.'</a>';
return $btn;
} elseif ($model->status = "Pending...") {
$sta = "btn-info";
$btn = '<a href="' . Url::home() . 'site/index?id=' . $model->id .'"
data-toggle="tooltip" title="Status" data-placement="bottom" class="btn btn-sm
'.$sta.' ">'.$model->status.'</a>';
return $btn;
} else {
$sta = "btn-danger";
$btn = '<a href="' . Url::home() . 'site/index?id=' . $model->id .'"
data-toggle="tooltip" title="Status" data-placement="bottom" class="btn btn-sm
'.$sta.' ">'.$model->status.'</a>';
return $btn;
}
}
},
],
but this one is giving an error that invalid parameter passed inside the foreach loop
Change the single = sign to 3 === signs.
So like this
if ($model->status === "Approved") {
$sta = "btn-success";
} elseif ($model->status === "Pending...") {
$sta = "btn-info";
} else {
$sta = "btn-danger";
}
By using only a single = you're assigning the value to the variable, so the first option will always be true.
The second one gives an error because $model->status contains a string value, not an array, so it can't be used in a foreach.

Why does my loop ignore and add NULL to every second item in the database?

I've inherited code from an old developer that was commented out and I've re-implemented it. A problem I've encountered is that the second item I'm putting in is registering the value as NULL.
The first two snippets of code are what I'm guessing is causing the issue for adding NULL for every second item being inserted into the database.
I have these three functions in the user model:
public function getDynamicVaribles() {
$string = null;
foreach ($this->userVariables as $var) {
$string .= $var->userTypeVariables->name . '=' . $var->value . "<br />";
}
return $string;
}
public function getDynamicVaribleValue($varName) {
foreach ($this->userVariables as $var) {
if ($var->userTypeVariables->name == $varName) {
return $var->value;
}
}
return null;
}
public function getDynamicVarible($varName) {
foreach ($this->userVariables as $userVariable) {
if ($userVariable->userTypeVariables->name == $varName) {
return $userVariable;
}
}
return null;
}
And I'm calling it like so in the _form view:
<?php
$varform = new DynamicForm();
$varform->attributes = $user->getDynamicFormConfig();
$varform->model_name = 'user';
echo $varform->run();
?>
And the function calling it in the my controller
foreach ($user->type->userTypeVariables as $userTypeVar) {
// Get fields for slide_varibles
// load Model here...
$slide_varible = $user->getDynamicVarible($userTypeVar->name);
// if ($slide_varible == null) {
// $slide_varible = new UserVariables;
// }
$slide_varible = new UserVariables;
$slide_varible->user_id = $user->id;
$slide_varible->value =
$_POST['user' . '_' . str_replace(' ', '_', $userTypeVar->name)];
$slide_varible->user_type_variables_id = $userTypeVar->id;
$slide_varible->save(false);
}
My attributes in the components (can probably be ignored):
foreach ($this->attributes as $attr) {
$attr['formname'] = $this->model_name . '_' . $attr['name'];
$attr['htmlOptions'] =
array('class' => 'span5', 'placeholder' => $attr['name']);
$attr['htmlOptions']['class'] .= ' form-control';
if ($attr['required'] === 1){
$attr['requiredfields'] = array('required' => true);
}else{
$attr['requiredfields'] = '';
}
// Per type input
// 'type'=>'text|radio|textarea|select'
if ($attr['type'] == 'text') {
echo '<div class="form-group">';
echo CHtml::label($attr['name'], $attr['formname'],
$attr['requiredfields']);
echo CHtml::textField($attr['formname'], $attr['value'],
$attr['htmlOptions']);
echo '</div>';
}
elseif ($attr['type'] == 'radio') {
echo '<div class="form-group">';
echo CHtml::label($attr['name'], $attr['formname'],
$attr['requiredfields']);
echo CHtml::radioButton($attr['formname'],
$attr['requiredfields']);
echo '</div>';
}
elseif ($attr['type'] == 'textarea') {
echo '<div class="form-group">';
echo CHtml::label($attr['name'], $attr['formname'],
$attr['requiredfields']);
echo CHtml::textArea($attr['formname'], $attr['value'],
$attr['htmlOptions']);
echo '</div>';
}
elseif ($attr['type'] == 'select') {
$items = explode(',', $attr['options']);
echo '<div class="form-group">';
echo CHtml::label($attr['name'], $attr['formname'],
$attr['requiredfields']);
echo CHtml::dropDownList($attr['formname'], $attr['value'],
array($items));
echo '</div>';
}
elseif ($attr['type'] == 'boolean') {
echo '<div class="form-group">';
echo CHtml::label($attr['name'], $attr['formname'],
$attr['requiredfields']);
echo CHtml::radioButtonList($attr['formname'], $attr['value'],
array('No' => 0, 'Yes' => 1));
echo '</div>';
}
}
The issue that I've encountered is that regardless of the dynamic form field type / or the input being put into this form, it's just adding NULL to the value field.
EDIT. The reason why the value was not being inserted is due to the full stop character "." was causing the database entry to go in as NULL.
After some testing and pure luck, I found out that the reason why the value was not posting to the database and resulting in a NULL Value, was the full stop character ".". Every other character I've tested results in the correct insert to the database.
As of posting I've not done any looking into why this is happening, but will update post if successful.

CakePHP Paginator Table Header Directional Icons

I'm trying to implement a function to be able to add directional (up / down) icons next to each of the table headers for a pagination table within CakePHP.
My current code is as follows:
$sort_key = $this->Paginator->sortKey();
$type = $this->Paginator->sortDir() === 'asc' ? 'up' : 'down';
function sortArrows($key, $title, $sort_key, $type)
{
$type_opposite = ($type === 'asc' ? 'down' : 'up');
if($key == $sort_key)
{
$icon = " <i class='fa fa-angle-" . $type . "'></i>";
}
else
{
$icon = " <i class='fa fa-angle-" . $type_opposite . "'></i>";
}
return "'$key', '$title' " . "$icon";
}
Which I am calling on the page as (on each of the table header fields):
<?php echo $this->Paginator->sort(sortArrows('street_suburb', 'Suburb', $sort_key, $type), array('escape' => false)); ?>
This produces the following error:
Notice (8): Array to string conversion [CORE/Cake/View/Helper/HtmlHelper.php, line 372]
I think I am quite close to what I need, I just cannot figure out what I am returning incorrectly from the function to get this to work.
Thanks
Inspired by your solution I have created a Helper extending PaginatorHelper to solve the problem.
Here is the code of file name MyPaginatorHelper.php:
<?php
namespace App\View\Helper;
use Cake\View\Helper\PaginatorHelper;
use Cake\Utility\Inflector;
class MyPaginatorHelper extends PaginatorHelper
{
public function sort($key, $title = null, array $options = [])
{
if (empty($title)) {
$title = $key;
if (strpos($title, '.') !== false) {
$title = str_replace('.', ' ', $title);
}
$title = __(Inflector::humanize(preg_replace('/_id$/', '', $title)));
}
$sortKey = $this->sortKey();
if (strpos($sortKey, '.') !== false) {
$sortKey = substr($sortKey, strpos($sortKey, '.')+1);
}
$sortDir = $this->sortDir() === 'asc' ? 'up' : 'down';
if($key == $sortKey)
{
$title .= " <i class='fa fa-angle-" . $sortDir . "'></i>";
$options['escape'] = false;
}
return parent::sort($key, $title, $options);
}
}
To use this helper you have to add this line in the AppView::initialize() method:
$this->loadHelper('Paginator', ['className' => 'MyPaginator']);
And then all the Paginator->sort() calls will have this feature by default.
I ended up coming up with a solution however I don't know if it is the best way around it. It does work however.
<?php
$sort_key = $this->Paginator->sortKey();
$type = $this->Paginator->sortDir() === 'asc' ? 'up' : 'down';
function sortArrows($key, $title, $sort_key, $type)
{
if($key == $sort_key)
{
$icon = " <i class='fa fa-angle-" . $type . "'></i>";
return $title . " " . $icon;
}
else
{
return $title;
}
}
?>
Called like:
<?php echo $this->Paginator->sort('street_suburb', sortArrows('street_suburb', 'Suburb', $sort_key, $type), array('escape' => false)); ?>

Making IDs unique in HTML

I'm such a noob at PHP. I'm really stuck on this and could do with some help!
I'm using the following code to control if a div class and span ID appears when a variable (e.g. $project1title and $project1description) is empty/not empty.
$html = '<div class="infobar"><div class="infobar-close"></div>';
$content = false;
if ($project1title !== '' && $project1description !== '')
{
$html .= '<span id="title"></span><span id="description"></span>';
$content = true;
}
// etc.
$html .= '</div>';
if ($content)
{
echo $html;
}
The code works fine when I've only got one project title & description there but when I start adding ($project2title !== '' && $project2description !== '') if ($project3title !== '' && $project3description !== ''), etc it messes up because I need a unique ID for each project title & description. My question is, how can I make each of them have a unique ID? (Would I need to use arrays?) And once I've given each project a unique ID, where in the code above would I need to declare each unique ID?
What about this :
<?php
$projects = array(
array(
'title' => 'myTitle',
'description' => 'my description',
),
array(
'title' => 'myTitle2',
'description' => 'my description2',
),
);
$html = '<div class="infobar"><div class="infobar-close"></div>';
$content = false;
$id = 1;
foreach($projects as $project){
if(!empty($project['title']) && !empty($project['description'])){
$html .= '<span id="title'. $id .'"></span><span id="description'. $id .'"></span>';
$content = true;
}
$id++;
}
$html .= '</div>';
if ($content) {
echo $html;
}
Note that if id is important for you, you can add an id key in the projects array.
Does that help ?
Alternatively, I think you should take a look at dynamic vars :
here is simple example of what you can do with them :
<?php
$html = '<div class="infobar"><div class="infobar-close"></div>';
$content = false;
for($i = 1;$i<=10;$i++){
$title = 'project' . $i . 'title';
$description = 'project' . $i . 'description';
if (isset($$title) && isset($$description) && $$title !== '' && $$description !== '')
{
$html .= '<span id="title'. $i .'"></span><span id="description'. $i .'"></span>';
$content = true;
}
}
$html .= '</div>';
if ($content)
{
echo $html;
}
Shouldn't the operations be:
!=
instead of
!==
?

Add class to this line... php/css

I have this line in php
<a title="'.htmlspecialchars($User->Name).'" href="'.$Href.'"'.$LinkClass.'>
I need to add another class which is known called tip
The code above generates something like this:
<a class="ProfileLink" href="/respond/profile/2/422" title="422">
As you can see $LinkClass gives me the class "ProfileLink" which is great
But I need to parse the class like "ProfileLink tip"
So just not sure how to amend $LinkClass above to something like $LinkClass tip
This is probably so basic I just cant see the wood for the trees
//
Edit: to add
Final html output needs to be :
<a class="ProfileLink tip" href="/respond/profile/2/422" title="422">
//
Added:
Entire php output for this function is:
if (!function_exists('UserPhoto')) {
function UserPhoto($User, $Options = array()) {
$User = (object)$User;
if (is_string($Options))
$Options = array('LinkClass' => $Options);
$LinkClass = GetValue('LinkClass', $Options, 'ProfileLink');
$ImgClass = GetValue('ImageClass', $Options, 'ProfilePhotoMedium');
$LinkClass = $LinkClass == '' ? '' : ' class="'.$LinkClass.'"';
$Photo = $User->Photo;
if (!$Photo && function_exists('UserPhotoDefaultUrl'))
$Photo = UserPhotoDefaultUrl($User);
if ($Photo) {
if (!preg_match('`^https?://`i', $Photo)) {
$PhotoUrl = Gdn_Upload::Url(ChangeBasename($Photo, 'n%s'));
} else {
$PhotoUrl = $Photo;
}
$Href = Url(UserUrl($User));
return '<a title="'.htmlspecialchars($User->Name).'" href="'.$Href.'"'.$LinkClass.'>'
.Img($PhotoUrl, array('alt' => htmlspecialchars($User->Name), 'class' => $ImgClass))
.'</a>';
} else {
return '';
}
}
}
How about using an array for the class attribute? Like this:
$LinkClass= array();
$LinkClassVal = GetValue('LinkClass', $Options, 'ProfileLink');
if($LinkClassVal){
$LinkClass[] = $LinkClassVal;
}
$LinkClass[] = "tip";
and then on return :
return '<a title="'.htmlspecialchars($User->Name).'" href="'.$Href.'"'.implode(" ",$LinkClass).'>'
.Img($PhotoUrl, array('alt' => htmlspecialchars($User->Name), 'class' => $ImgClass))
.'</a>';

Categories