Yii 2 dropdown value safe newbie - get

I heard building Data in View is not very good, but anyway, i am wondering why its not working:
View
<?php $form = ActiveForm::begin();
$alleSpieler = \common\models\Spieler::find()->all();
if ($alleSpieler) {
unset($types);
foreach ($alleSpieler as $value) {
$types[$value->id] = $value->email . ' ' . $value->vorname . ' ' . $value->nachname;
}
}
echo $form->field($model, 'spielerId')->dropDownList($types, 'prompt'=>'Spieler manuell hinzufügen']);
ActiveForm::end();
?>
<?= AnmeldungDurchfuehrung2::widget(['durchfuehrungId' => $model->id, 'spielerId' => $model->spielerId]) ?>
Model
public $spielerId;
But spielerId ist not set in my Case. If i, for example, set 'spielerId' => 1120 in the widget call, it is working. But if i want the value from the dropdownlist, the action is saying that spielerId is missing. I am newbie and perhaps i forgot something? Thank you!

You must add $spielerId; in validation array in your model, som like this:
public function rules()
{
return [
[['spielerId'], 'integer'], //type of atribute value
[['spielerId'], 'required'], //if need
/*... other atributes ...*/
];
}
for more detail check the documentation.

okay now i know what i need:
echo $form->field($model, 'spielerId')->dropDownList($types,['prompt'=>'Waehlen Sie einen Spieler']);
echo Html::submitButton('Auswählen', ['class' => 'btn btn-primary']);
This is my Dropdown.
I need something like:
<?php if(!empty($_GET['spielerId'])) {
echo AnmeldungDurchfuehrung2::widget(['durchfuehrungId' => $model->id, 'spielerId' => $_GET['subject']]); }?>

Related

Prevent CakePHP from stripping chars from url passed as param?

I am developing an application using CakePHP 2.6 and having issues with passing a string containing url characters as a parameter through to a controller method.
In my view I have a chunk of code which echoes out a series of table rows containing data and passes through the page id, unit id and the id of the link which can sometimes contain a url.
<?php foreach($linklist as $l) { ?>
<tr id="Link_<?php echo $l['ID']; ?>">
<td><?php echo $l['Title']; ?></td>
<td class="buttontd"><?php echo $this->Form->postlink('Delete', array('action' => 'deletelink', $this->request->params['pass'][0], $results[0]['PageUnitTypeID'], $l['ID']), array('class' => 'button delete')); ?></td>
</tr>
<?php } ?>
When the postlink button passes the information over to the 'deletelink' action in the controller the url looks like this:
http://mydomainname.com/webpages/deletelink/239/7/urlhttp%3A%2F%2Fwww.google.co.uk%2F
Which shows that the url has been passed as the string but then in the action when I try to just var_dump() the third parameter it returns a string of www.google.co.uk and nothing more which is preventing me from doing a substr() call on the parameter to check if the first 3 characters are equal to url or not.
I have tried to wrap the parameter in the postlink call inside serialize() and urlencode() but neither has had the desired effect of returning the full string as
urlhttp%3A%2F%2Fwww.google.co.uk%2F
Does anyone know of a successful way to pass through a parameter like this without losing important characters?
Update 1: Deletelink action
public function deletelink($pid = null, $uid = null, $lid = null) {
$this->autoRender = false;
if (!is_null($pid) && is_numeric($pid) && !is_null($uid) && is_numeric($uid)) {
if (!is_null($lid)) {
if (substr($lid, 0, 3) == 'url') {
echo substr($lid, 0, 3);
} else {
echo substr($lid, 0, 3);
}
} else {
$this->Session->setFlash('It is unknown which link you wish to delete from the webpage', 'flash_message_bar', array('class' => 'error'));
return $this->redirect(array('action' => 'edit', $pid));
}
} else {
$this->Session->setFlash('It is unknown which on which webpage you wish to delete a link', 'flash_message_bar', array('class' => 'error'));
return $this->redirect(array('action' => 'index'));
}
}
CakePHP (or mod_rewrite I would say) is getting confused with the way your URL is formed.
Your safest option is to base64_encode the url parameter in the view, which will result in call similar to:
http://mydomainname.com/webpages/deletelink/239/7/dXJsaHR0cDovL3d3dy5nb29nbGUuY28udWsv
and base64_decode it later in the action, which will transform
dXJsaHR0cDovL3d3dy5nb29nbGUuY28udWsv
into
urlhttp://www.google.co.uk/

How to get all posts in selected taxonimies custom post type?

I have a post type called 'faq' and taxonomy called 'type' within my template and a few taxonomy terms created "Design", "Print", "Display" etc.
The idea I am trying to implement is to display only the posts that belong to assigned taxonomies (types) without duplication. Each post may be assigned to multiple taxonomies (types).
My current code works fine as long as the post have got only one taxonomy assigned to it. As soon as I assign more then one taxonomy it shows duplicate posts like this:
Question 6
Question 5
Question 1
Question 1
Here is my current code:
<?php
$post_type = 'faq';
$tax = 'type';
$faq_types = get_field('types');
$filtered = array();
$termargs = array( 'include' => $faq_types );
$tax_terms = get_terms($tax, $termargs);
if ($tax_terms) {
$i = 1;
foreach ($tax_terms as $tax_term) {
$args=array(
'post_type' => $post_type,
$tax => $tax_term->slug,
'post_status' => 'publish',
'posts_per_page' => -1,
'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div class="accordion-section">
<a class="accordion-section-title" href="#accordion-<?php echo $i; ?>"><i class="fa fa-chevron-right"></i> <?php the_title(); ?></a>
<div id="accordion-<?php echo $i; ?>" class="accordion-section-content">
<?php the_content(); ?>
</div>
</div>
<?php
$i++;
endwhile;
}
wp_reset_query();
}
}
?>
I'd really appreciate any help with getting this working the way I need.
Your current loop is saying "For each taxonomy term, show all posts associated with that term", so of course it will duplicate if there is one post associated with multiple terms. Take your query out of the foreach loop and use a single tax query with an array of terms:
$args = array(
'post_type' => $post_type,
'tax_query' => array(
array(
'taxonomy' => $tax,
'field' => 'slug',
'terms' => $term_slugs,
),
),
'post_status' => 'publish',
'posts_per_page' => -1,
'caller_get_posts'=> 1
);
EDIT
By the way, you'll need to convert your array of term objects to an array of term slugs for this to work properly:
$term_slugs = array();
foreach( $tax_terms as $term ) {
$terms_slugs[] = $term->slug;
}

What is the proper way to do conditional formatting in a ZF2 MVC project?

In a ZF2 project I am developing, I would like to create a shell around the echo $this->content; statement in layout.phtml that would allow conditional formatting of the main content area. Specifically, I want to put the content into a column that is 75% wide and include some “ornamental” elements in a column that is 25% wide for most of the pages. However, I want to change to a single column for pages that need more space. My project is a CMS in which each page has an attribute that can tell either the view or the controller whether the page should be normal or wide. I have considered a number of methods for achieving what I’m after.
My “conditional formatting in the layout view” might look like this:
// module/Application/view/layout/layout.phtml:
//...
if ($templateNormal) {
echo "<div class='col-md-9'>";
} else {
echo "<div class='col-md-12'>";
}
echo $this->content;
if ($templateNormal) {
echo "</div>";
echo "<div class='col-md-3'>";
//... ornamentation
echo "</div>";
} else {
echo "</div>";
}
//...
While the above-method could work, for pure MVC I don’t think there is supposed to be any decision-making going on in the layout view.
My “conditional formatting in partial views” could look like this:
// module/Application/view/layout/layout.phtml:
//...
echo $this->partial('partial/open-shell.phtml');
echo $this->content;
echo $this->partial('partial/close-shell.phtml');
//...
// module/Application/view/partial/open-shell.phtml:
if ($templateNormal) {
echo "<div class='col-md-9'>";
} else {
echo "<div class='col-md-12'>";
}
// module/Application/view/partial/close-shell.phtml:
if ($templateNormal) {
echo "</div>";
echo "<div class='col-md-3'>";
//... ornamentation
echo "</div>";
} else {
echo "</div>";
}
Here the decision-making is taken out of the layout view, but it is simply put into other views so it's still in the view package and still not pure MVC.
In my “conditional formatting in the controller” solution, a pair of html script strings are developed in a controller function, and then passed on to the view. It might look like this:
// module/Application/view/layout/layout.phtml:
//...
echo $this->open-shell-script';
echo $this->content;
echo $this->close-shell-script';
//...
// some controller function:
//...
if ($templateNormal) {
$open-shell-script = "<div class='col-md-9'>";
$close-shell-script = "</div>";
$close-shell-script = "<div class='col-md-3'>";
$close-shell-script .= //... ornamentation
$close-shell-script .= "</div>";
} else {
$open-shell-script = "<div class='col-md-12'>";
$close-shell-script = "</div>";
}
//...
In this method, the decision-making is done in the controller where I assume it should be, but it seems odd to be writing html there.
Any comments or suggestions?
create two layout and in init() method of Module.php decide which layout should use .
public function init(ModuleManager $moduleManager) {
$sharedEvents = $moduleManager->getEventManager()->getSharedManager();
$sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
// This event will only be fired when an ActionController under the MyModule namespace is dispatched.
$controller = $e->getTarget();
$controller->layout(" your chose layout ");
}
}
There are many ways to accomplish this. This is one method and the logic lives in the controller:
controller
public function yourSampleAction()
{
// assign variables as usual to this view model
$viewModel = new ViewModel(array(
//vars
);
// this will be the "wrapper" and can be single, double column or anything else.
$wrapperViewModel = new ViewModel();
$wrapperViewModel->addChild($viewModel, 'innerContent');
// use this line when you want one column
$wrapperViewModel->setTemplate('path/to/your/single-column-wrapper.phtml');
// when this line you want two columns
$wrapperViewModel->setTemplate('path/to/your/two-column-wrapper.phtml');
return $wrapperViewModel;
}
two-column-wrapper.phtml
<div class='col-md-9'>
<?php echo $innerConntent; ?>
</div>
<div class='col-md-3'>
<!--- something else in here? -->
</div>
single-column-wrapper.phtml
<div class='col-md-12'>
<?php echo $innerConntent; ?>
</div>
Instead of setting different templates, you can adjust the Bootstrap Twitter classes by making the necessary classes dependent on a layout variable. You can use the logic in your controllers action to pass variables directly to the layout (not the view) like so:
$this->layout()->setVariables
(
array
(
'layoutVar1' => 75,
'someColClass' => ($someSwitch ? 'col-md-9':'col-md-12' ),
'layoutVar1' => 75,
)
);
and then just access these variables in the Layout as you would variables sent to the View. You don't have to even prepend them with "layout", they won't clash.

Attributes of products in cart in opencart

I am rather new to opencart and I'm currently developing a shop where I need to be able to display product attributes inside the cart. I searched allover but apparently no one had the need for this feature.
I short, i tried to duplicate the way attributes are retrieved in the product page but no success.
I modified the controller adding this line:
$this->data['attribute_groups'] = $this->model_catalog_product->getProductAttributes($this->request->get['product_id']);
I also added:
<?php foreach ($attribute_groups as $attribute_group) { ?>
<?php echo $attribute_group['name']; ?>
<?php foreach ($attribute_group['attribute'] as $attribute) { ?>
<?php echo $attribute['name']; ?>
<?php echo $attribute['text']; ?>
<?php } ?>
<?php } ?>
<?php } ?>
with no succes.
I guess I have to modify somehow system/library/cart.php. The problem is that I am not savvy enough to know how to do it!
At this point I decided to ask for help here!
Any ideas please?
This isn't as hard as it would seem on the surface you'll only need to edit 2 files and open 3.
--1-- Add the method for retrieving attributes to the cart class.
Open catalog/model/catalog/product.php
Find the method getProductAttributes($product_id) and copy the entire method to your clipboard.
Open system/library/cart.php and after the getProducts() method paste your copied method.
--2-- Just above where you pasted the code, at the end of the getProducts() method you'll see where the products array is built for the view, it looks similar to this:
$this->data[$key] = array(
'key' => $key,
'product_id' => $product_query->row['product_id'],
'name' => $product_query->row['name'],
'model' => $product_query->row['model'],
'shipping' => $product_query->row['shipping'],
'image' => $product_query->row['image'],
'option' => $option_data,
'download' => $download_data,
'quantity' => $quantity,
'minimum' => $product_query->row['minimum'],
'subtract' => $product_query->row['subtract'],
'stock' => $stock,
'price' => ($price + $option_price),
'total' => ($price + $option_price) * $quantity,
'reward' => $reward * $quantity,
'points' => ($product_query->row['points'] ? ($product_query->row['points'] + $option_points) * $quantity : 0),
'tax_class_id' => $product_query->row['tax_class_id'],
'weight' => ($product_query->row['weight'] + $option_weight) * $quantity,
'weight_class_id' => $product_query->row['weight_class_id'],
'length' => $product_query->row['length'],
'width' => $product_query->row['width'],
'height' => $product_query->row['height'],
'length_class_id' => $product_query->row['length_class_id']
);
Now simply add a call to that getAttributes method to the array:
'attributes' => $this->getProductAttributes($product_query->row['product_id'])
Now open your cart template: catalog/view/theme/yourtheme/common/cart.tpl and right where the product option loop is, you can now loop through your attributes just like the options.

Yii Search in navigation menu

I'm currently writing an application in Yii in which i want to create a search box in the header (either in the navigation menu or just above it). This search box should be able to be accessed from every part of the site, and it should be able to search on different columns of different tables.
I have no idea on how to do this, and almost all posts on the web about it involves using the grid-view, or an extension (I'd like to create the code without an extension if that's possible).
Do you have an idea to how the search code should look (what i should put in which controller etc.)?
-- EDIT --
I still don't know how to do this but I will show you what I have at the moment anyway. It is not much and it is pretty obvious where i am missing some code.
/view/layout/main.php:
<?php echo CHtml::form(Yii::app()->createUrl('product/search'), 'get') ?>
<?php echo CHtml::textField('search_key','',array('placeholder' => 'Search')); ?>
<?php echo CHtml::submitButton('Go'); ?>
<?php echo CHtml::endForm() ?>
/view/product/search.php:
//Not sure by any means what to write here, but I'll like a list view populated with the search results
/controllers/productController.php
/**
* Search through model.
*/
public function actionSearch()
{
if(isset($_GET['search_key'])){
$search = $_GET['search_key'];
$model->name = $search;
}
$this -> render('search', array(
'model' => $model,
));
}
/models/Product.php
/**
* Retrieves a list of models based on the current search/filter conditions.
* #return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('name',$this->name,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
You can perform like this:
Find #mainmeu in /protected/views/layout/main.php
<div id="mainmenu">
<div style="width: 80%;float: right">
<?php $this->widget('zii.widgets.CMenu',array(
'items'=>array(
array('label'=>'home', 'url'=>array('/site/index')),
array('label'=>'about', 'url'=>array('/site/page', 'view'=>'about')),
array('label'=>'contact', 'url'=>array('/site/contact')),
),
)); ?>
</div>
<div style='float: left;direction: rtl; color: #ffffff; margin: 5px 0 0 5px; font-size: 13px'>
<?php echo CHtml::form(Yii::app()->createUrl('product/search'),'get') ?>
<?php echo CHtml::textField('search_key', 'search') ?>
<?php echo CHtml::submitButton(); ?>
<?php echo CHtml::endForm() ?>
</div>
</div><!-- mainmenu -->
Edit:
/models/Product.php:
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('name',$this->name,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/controllers/productController.php -> actionSearch():
public function actionSearch()
{
$model = new Product('search');
$model->unsetAttributes();
if(isset($_GET['search_key']))
$model->name = $_GET['search_key'];
$this -> render('search', array(
'model' => $model,
));
}
/view/product/search.php:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'product-grid',
'dataProvider'=>$model->search(),
//'filter'=>$model,
'columns'=>array(
'name',
array(
'class'=>'CButtonColumn',
),
),
)); ?>

Resources