Kohana "has many through" relation - kohana

I was wondering what the best method is to edit a 'has many through' relation with a form.
Let's say I have a bunch of users that can belong to multiple categories.
The form would have some checkboxes like this:
<input type="checkbox" name="category_ids" value="1" />
<input type="checkbox" name="category_ids" value="2" />
Then in my controller I could do something like:
// dump all relations
DB::delete('users_categories')->where('user_id','=',$user->id)->execute();
// add new relations
foreach (explode(',', $_POST['category_ids']) as $category)
$user->add('category', ORM::factory('category', $category))
But this looks too complicated to me (also because I have more than one 'has many through' relations). Is there an easier / better way to accomplish this using kohana orm? :)

thats how i do it
// C
$roles = ORM::factory('role')->find_all();
foreach ($roles as $role)
{
$action = isset($form['user']['roles'][$role->id]) ? 'add' : 'remove';
// you dont need this if-statement if you'r using ko2
if ($action === 'add' && $user->has('roles', $role))
{
continue;
}
$user->$action('roles', $role);
}
// V
<?
$roles = ORM::factory('role')->find_all();
foreach ($roles as $role):
?>
<?= form::checkbox('user[roles]['.$role->id.']', $role->id, $user->has('roles', $role)) ?>
<?= form::label('user_roles_'.$role->id, $role->name) ?>
<br />
<? endforeach ?>

To find what was added (reverse the args to find what was removed) consider using array_diff().
With this you should be able to code something more efficient than pure orm.

Related

Pagination page/2 not found for a category but works for tags?

This drives me nuts, i am trying to list post based on a category an on a tag. Now for tag i have got it working. Using archive.php but for the category, using categroy.php, it doesn't work for page/2???.
I have already check the permalinks and indeed if i use the default settings both mydomain.com/blog/page/2 and mydomain.com/tag/green/page/2 work. But turning on /%category%/%postname%/ and the mydomain.com/blog/page/2 gives a page not found???
Here's the main part of category.php (which is the same as archive.php)
global $wp_query;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts(array(
'posts_per_page' => 3,
'paged' => $paged
));
while (have_posts()) : the_post();
// Include the page content template.
get_template_part('partials/content', 'loop');
// End the loop.
endwhile;
?>
<!-- Pagination -->
<div class="navigation">
<div class="alignleft"><?php next_posts_link('« Older Entries') ?></div>
<div class="alignright"><?php previous_posts_link('Newer Entries »') ?></div>
</div>
<?php if ($wp_query->max_num_pages > 1) : $paged = intval(get_query_var('paged')); ?>
<div class="older"><?php next_posts_link(__('Older entries', 0)); ?></div>
<!--test this one-->
<?php if ($paged > 1) : ?>
<div class="newer"><?php previous_posts_link(__('Newer entries', 0)); ?></div>
<?php endif;
endif;
?>
<!-- End Pagination -->
The codex contains the following important note on query_posts:
Note: This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination). Any modern WP code should use more reliable methods, like making use of pre_get_postshook, for this purpose.
If you follow that instruction, you should be able to fix your problem yourself

disable layout for particular pages in ZF2

How to disable particular layout(example:menus.phtml) for particular pages in controller in ZF2?? In the below example menus.phtml should be disable for specific pages. Remaining pages must contain menus.phtml like header and footer.
<div>
header.phtml
</div>
<div>
menus.phtml
</div>
<div>
<?php echo $this->content; ?>
</div>
<div>
footer.phtml
</div>
There are various aproaches to this. Also modules.zendframework has quite a few modules here that may help you out.
If you are still keen on writing that yourself you could add variables to your layout within your controllers like so:
<?php
//YourController.php
public function someAction()
{
...
$this->layout()->footer = 'default';
...
}
//layout.phtml
<?php if ($this->footer === 'default') : ?>
//show the footer
<?php endif; ?>
Doing this is pretty inefficient though. Just imagine you'd need to do this to every action in all the controllers... I sure would not like to do that.
Now zf2 has a service and event layer that could help us out quite a bit here. This is a pretty nice read and introduction to it. You'd just write a service and trigger a event on your controllers/routes/whatever. Now you would also probably like to configure what is shown and what is hidden right? Thats pretty easy, too. Just write yourself a config file and merge it with the global.config like so:
<?php
//CustomModule/module.php
public function getConfig() {
$config = array();
$configFiles = array(
include __DIR__ . '/config/module.config.php',
include __DIR__ . '/config/module.customconfig.php',
);
foreach ($configFiles as $file) {
$config = \Zend\Stdlib\ArrayUtils::merge($config, $file);
}
return $config;
}
Source: Where to put custom settings in Zend Framework 2?
First, get the controller or action name:
$controllerName =$this->params('controller');
$actionName = $this->params('action');
then in your layout/view script add a simple logic.
<?php if ($actionName != 'action that you want to disable the layout/menu'): ?>
echo $this->render('menus.phtml');
<?php endif; ?>

$wpdb not seeming to work with

I'm using the following code to populate a WordPress dropdown menu with all the unique values from a custom field:
<form name="search" action="" method="get">
<select name="stateprov">
<option>Select...</option>
<?php
$metakey = 'state_prov';
statesProvs = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_value ASC", $metakey) );
if ($statesProvs) {
foreach ($statesProvs as $stateprov) {
echo "<option value=\"" . $stateprov . "\">" . $stateprov . "</option>";
}
}
?>
</select>
<input type="submit" value="search" />
</form>
However, it takes nothing from the DB so the popup list is empty.
Trying a different query like
$statesProvs = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_author = 2" );
Works as expected. I get a popup with a bunch of Post ID's in it. But the query that's supposed to work on my custom metadata just brings up an empty menu (and print_r reveals an empty array).
The data is definitely in the DB... what am I doing wrong?
It may also be significant that I'm using a custom metabox PHP class that writes all the custom-created field keys and values into the value of the _custom_meta metakey. If I've put that correctly. Thus:
a:61:{s:10:"state_prov";s:2:"CA";s:13:"vertical_drop";s:13:"3100ft / 945m";s:14:"base_elevation";s:14:"7953ft / 2424m";s:16:"summit_elevation";s:15:"11053ft / 3369m";s:12:"skiable_area";s:10:"3500 acres";s:16:"average_snowfall";s:14:"400in / 1016cm";s:13:
Etc. Is this way of storing the custom metadata preventing wpdb from accessing it properly?
Thanks!
you must use global $wpdb before you start the wpquery, refer codex for more details
<form name="search" action="" method="get">
<select name="stateprov">
<option>Select...</option>
<?php
global $wpdb;
$metakey = 'state_prov';
$wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_value ASC", $metakey) );
if ($statesProvs) {
foreach ($statesProvs as $stateprov) {
echo "<option value=\"" . $stateprov . "\">" . $stateprov . "</option>";
}
}
?>
</select>
<input type="submit" value="search" />
</form>
Etc. Is this way of storing the custom metadata preventing wpdb from
accessing it properly?
Yes.
In general, Wordpress isn't capable of searching or sorting through serialized PHP arrays.
The most viable solution here is to store this data point ('state_prov') in its own custom field. This will allow you to naturally search and sort using $wpdb. It also seems like you want this custom field to be private/hidden, in which case you'll want to prefix it with an underscore: '_state_prov'.
Another option, assuming the above isn't viable for your needs, is to use MySQL String Functions; but this is far from ideal or optimized (especially if the database grows significantly.) Rough, untested example below.
// Assuming all state_prov are exactly 2 characters in length
$identifier = 's:10:"state_prov";s:2:"';
$identifier_length = strlen($identifier);
$wpdb->get_col($wpdb->prepare("SELECT DISTINCT(SUBSTR(`meta_value`, INSTR(`meta_value`, '$identifier')+$identifier_length, 2)) as `state_prov` FROM $wpdb->postmeta WHERE `meta_key`=%s ORDER BY `state_prov` ASC", $metakey) );

How to display content from a child page within a hierarchial custom post type?

I have a hierarchical custom post type. It has 6 pages, and each page has 3 child pages.
When viewing one of the 6 pages, I need to display content (a title and excerpt) from each of its 3 child/descendent pages.
Here is my current loop:
<?php if(have_posts()):?>
<?php query_posts('&post_type=how-we-do-it&post_parent=0');?>
<?php while(have_posts()):the_post();?>
<?php $color = get_post_meta( get_the_ID(), 'pointb_how-we-do-it-color', true ); ?>
<div class="section">
<div class="title">
<h1 style="background:<?php echo $color;?> !important;">
<?php the_title();?>
</h1>
</div>
<div class="content">
<div class="how-<?php the_slug();?>">the summary here. and here is child content:
<div class="child">child content should be here.</div>
</div>
</div>
</div>
<?php endwhile;?>
<?php wp_reset_query(); ?>
<?php endif;?>
I have tried numerous different approaches to try and accomplish what I need, but none of them work within the custom post type. Here are some of the various methods I have tried:
I tried the suggested code on this page: http://wordpress.org/support/topic/display-child-pages-title-amp-content-on-parent-page
I also tried the following code:
$pageChildren = get_pages('child_of='.$post->ID');
if ( $pageChildren ) {
foreach ( $pageChildren as $pageChild ) {
echo '<h2>'. $pageChild->post_title.'</h2>
';
if ($pageChild->post_excerpt){
echo ''.$pageChild->post_excerpt.'
';
}
}
}
I've tried a number of other methods that I didn't bother saving, so I can't show them.
I'm at the point where I am getting frustrated with this and thought I'd throw it out here to get some fresh perspectives.
The issue with your first sample is that you call if(have_posts()) before you reconstruct the query.
The second sample has a dangling ' after $post->ID.
Try this:
$pageChildren = get_posts( 'post_type=how-we-do-it&post_parent='.$post->ID );
Based on some comments from MarZab above, I got thinking about the post ID.
I made the following tweak to the block of code I originally posted above, and now it works perfectly:
$pageChildren = get_pages('child_of='.$post->ID');
Is now:
$post_id = get_the_ID();
$pageChildren = get_posts( 'post_type=how-we-do-it&echo=0&post_parent='.$post_id );

Hiding some configurable attribute in the front-end - magento

Please help...anyone
I have a problem with hiding some configurable attributes:
These are my configurable attributes at the back-end:
Shape/Type
Grit & Colour
Shank
Items pack
Diameter
Supplier
My client wants to hide the "Manufacturer" attribute on the front-end
but wants to import the supplier at the back-end.
Please see the website I am working:
http://ridental.com.au/newsite/polishers.html/
I managed to hide it from front-end by just adding some if statement
like this: in the app\design\frontend\default\MYTEMPLATE\template\catalog\product\view\type\options\configurable.phtml
<?php
$_product = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
<dl class="outer">
<dl class="inner">
<?php foreach($_attributes as $_attribute): ?>
<?php $attCode = $_attribute->getProductAttribute()->getFrontend()->getAttribute()->getAttributeCode(); ?>
<?php if($attCode != "manufacturer"):?>
<div class="dtdd-wrapper<?php if ($_attribute->decoratedIsLast){echo " last";}?>">
<dt><label class="required"><em>*</em><?php echo $_attribute->getLabel() ?></label></dt>
<dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
<div class="input-box">
<select name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select">
<option><?php echo $this->__('Choose an Option...') ?></option>
</select>
</div>
</dd>
</div>
<?php endif; ?>
<?php endforeach; ?>
</dl>
</dl>
<script type="text/javascript">
[b]var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);[/b]
</script>
The Manufacturer will not be displayed on the front-end.
But when I click Add to Cart button I got the error:
Please specify the product's option(s).
I noticed that in:
var spConfig = new Product.Config(<?php echo $this->getJsonConfig()
It is still referring to the attribute "supplier" and waiting for the user response to choose Manufacturer in the drop down.
that's why I get the error: Please specify the product's option(s).
My question:
Is it possible to filter the function getJsonConfig()?
let say not include the:
if ($attributecode != 'manufacturer'){
do some stuff.....
}
I copied a local version of this function and now found in: app\code\local\Mage\Catalog\Block\Product\View\Type\Configurable.php
Please help...if anyone accomplished this kind of problem.
I tried extending getJsonConfig() to filter some attribute like "supplier" but to no avail.
Am I doing the right thing?
Chances are, from what you are describing, you should remake the configurable product without using the "Supplier" attribute.
When you make a configurable product, the first screen that allows you to mark attributes with check boxes is meant to define what the configurable product will be filtering, the attributes will still be attached to the product information.

Resources