Auto complete/Suggest in Wordpress Form - autocomplete

I'm placing a search form of 6 fields on my home page which includes a text box field named course. I want to show course suggestions while user typing. One more is, I want to show/hide some fields according to the option of first field dropdown. Any help would be appreciated.

You can use jQuery Auto Suggest which is included with WordPress : wp_enqueue_script
With this you can write a form that does a Ajax lookup to the the Ajax URL handler. Which you can add_action onto. AJAX in Plugins
So you can ajax lookup and then on the action side you can just perform a get_posts to match titles, or a raw sql Query. And return what is needed. edit your functions.php.
add_action('wp_enqueue_scripts', 'se_wp_enqueue_scripts');
function se_wp_enqueue_scripts() {
wp_enqueue_script('suggest');
}
add_action('wp_head', 'se_wp_head');
function se_wp_head() {
?>
<script type="text/javascript">
var se_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery(document).ready(function() {
jQuery('#se_search_element_id').suggest(se_ajax_url + '?action=se_lookup');
});
</script>
<?php
}
add_action('wp_ajax_se_lookup', 'se_lookup');
add_action('wp_ajax_nopriv_se_lookup', 'se_lookup');
function se_lookup() {
global $wpdb;
$search = like_escape($_REQUEST['q']);
$query = 'SELECT ID,post_title FROM ' . $wpdb->posts . '
WHERE post_title LIKE \'' . $search . '%\'
AND post_type = \'post_type_name\'
AND post_status = \'publish\'
ORDER BY post_title ASC';
foreach ($wpdb->get_results($query) as $row) {
$post_title = $row->post_title;
$id = $row->ID;
$meta = get_post_meta($id, 'YOUR_METANAME', TRUE);
echo $post_title . ' (' . $meta . ')' . "\n";
}
die();
}

Use ajax for both. You may have to write some mysql query to retrieve the required fields(post titles or whatever it is) from the table.

Related

how to set a value for Zend_Form_Element_Submit (zendframework 1)

I have am having trouble setting the basic values of a zend form element submit button (Zendframework1). I basically want to set a unique id number in it and then retrieve this number once the button has been submitted.
Below is my code. you will nots that I tried to use the setValue() method but this did not work.
$new = new Zend_Form_Element_Submit('new');
$new
->setDecorators($this->_buttonDecorators)
->setValue($tieredPrice->sample_id)
->setLabel('New');
$this->addElement($new);
I would also appreciate any advice on what I use to receive the values. i.e what method I will call to retrieve the values?
The label is used as the value on submit buttons, and this is what is submitted. There isn't a way to have another value submitted as part of the button as well - you'd either need to change the submit name or value (= label).
What you probably want to do instead is add a hidden field to the form and give that your numeric value instead.
It's a little bit tricky but not impossible :
You need to implement your own view helper and use it with your element.
At first, you must add a custom view helper path :
How to add a view helper directory (zend framework)
Implement your helper :
class View_Helper_CustomSubmit extends Zend_View_Helper_FormSubmit
{
public function customSubmit($name, $value = null, $attribs = null)
{
if( array_key_exists( 'value', $attribs ) ) {
$value = $attribs['value'];
unset( $attribs['value'] );
}
$info = $this->_getInfo($name, $value, $attribs);
extract($info); // name, value, attribs, options, listsep, disable, id
// check if disabled
$disabled = '';
if ($disable) {
$disabled = ' disabled="disabled"';
}
if ($id) {
$id = ' id="' . $this->view->escape($id) . '"';
}
// XHTML or HTML end tag?
$endTag = ' />';
if (($this->view instanceof Zend_View_Abstract) && !$this->view->doctype()->isXhtml()) {
$endTag= '>';
}
// Render the button.
$xhtml = '<input type="submit"'
. ' name="' . $this->view->escape($name) . '"'
. $id
. ' value="' . $this->view->escape( $value ) . '"'
. $disabled
. $this->_htmlAttribs($attribs)
. $endTag;
return $xhtml;
}
}
So, you assign the helper to the element :
$submit = $form->createElement( 'submit', 'submitElementName' );
$submit->setAttrib( 'value', 'my value' );
$submit->helper = 'customSubmit';
$form->addELement( $submit );
This way, you can retrieve the value of the submitted form :
$form->getValue( 'submitElementName' );

How to filter New WP Query by Custom Field Value?

I am creating new pages for each of my categories in wordpress. The post editor has a custom field that allows the selection of a sector type, this gets applied to the post on update. The custom field key is: sector, for custom field meta value options lets use SectorA, SectorB and SectorC. I am using a custom post type called projects.
I followed the advice at this link http://weblogtoolscollection.com/archives/2008/04/13/how-to-only-retrieve-posts-with-custom-fields/
How can I change the query line in the code below so that it filters the loop by a Sector name, lets use SectorA. I'll then reuse the code on each template page changing the value to SectorB and SectorC on the other pages.
I think this needs changing somehow:
$customPosts->query('showposts=5&sector=sectorA&post_type=projects' );
Currently it echos the sector value and description value successfully but is showing all the posts. So my attempt to limit it to sectorA using sector=sectorA doesn't seem to work?
This code is in functions.php:
function get_custom_field_posts_join($join) {
global $wpdb, $customFields;
return $join . " JOIN $wpdb->postmeta postmeta ON (postmeta.post_id = $wpdb->posts.ID and postmeta.meta_key in ($customFields)) ";
}
function get_custom_field_posts_group($group) {
global $wpdb;
$group .= " $wpdb->posts.ID ";
return $group;
}
And this code is on the Template Page:
<?php /* Begin Custom Field Posts */ ?>
<h2>Custom Posts</h2>
<ul>
<?php
global $customFields;
$customFields = "'sector', 'description'";
$customPosts = new WP_Query();
add_filter('posts_join', 'get_custom_field_posts_join');
add_filter('posts_groupby', 'get_custom_field_posts_group');
$customPosts->query('showposts=5&sector=sectorA&post_type=projects' );//Uses same parameters as query_posts
remove_filter('posts_join', 'get_custom_field_posts_join');
remove_filter('posts_groupby', 'get_custom_field_posts_group');
while ($customPosts->have_posts()) : $customPosts->the_post();
$sector = get_post_custom_values("sector");
$description= get_post_custom_values("description");?>
<li><?php echo $sector[0]; ?></li>
<li><?php echo $description[0]; ?></li><br />
<?php endwhile; ?>
</ul>
<?php /* End Custom Field Posts */ ?>
Thanks for your help
May be this what you want
function get_custom_field_posts_join($join) {
global $wpdb, $customSector;
return $join . " JOIN $wpdb->postmeta postmeta ON (postmeta.post_id = $wpdb->posts.ID and postmeta.meta_key = 'sector' and postmeta.value = '$customSector') ";
}
and modification of page
$customSector='sectorA';//<--- insert this
add_filter('posts_join', 'get_custom_field_posts_join');
Try using this code.
<?php
$sector = get_post_meta($post->ID, "sector", false);
if ($sector[0]=="") { ?>
<!-- If there are no custom fields, show nothing -->
<?php } else { ?>
<div class="sector">
<h3>Title</h3>
<?php foreach($sector as $sector) {
echo '<blockquote><p>'.$sector.'</p></blockquote>';
} ?>
</div>
<?php } ?>

Zend_Navigation rendering submenu with partial

I've posted an edit to my question. While working on it I noticed the problem is easy to simplify.
I need a custom format of my submenu so i have to use partial. But then the problem occurs.
The below code shows the INCORRECT level (0):
echo $this->navigation()->menu()
->setMinDepth(1)
->setMaxDepth(1)
->setRenderParents(false)
->setOnlyActiveBranch(true)
->renderPartial(null, array('partials/menu.phtml', 'default'));
The below code shows the CORRECT menu level (1)
echo $this->navigation()->menu()
->setMinDepth(1)
->setMaxDepth(1)
->setRenderParents(false)
->setOnlyActiveBranch(true)
->render();
Any ideas? Guys please. I would appreciate any help!
Edit
My partials/menu.phtml:
foreach ($this->container as $page)
{
$active = $page->isActive();
echo '<div class="item">';
echo '<a class="'. ($active ? 'active' : '') .'" href="' . $this->baseUrl($page->getHref()) . '">' . $page->getLabel() . '</a>';
echo '</div>';
}
EDIT 2
My understanding of Zend_Navigation was, first to prepare container and than put it through partial.
$nav = $this->navigation()->menu()->setOnlyActiveBranch(true)->getContainer();
echo $this->navigation()->menu()->renderPartial($nav, array('/partials/menu.phtml', 'default'));
What is the point of setting set{Min/Max}Depth, parentRendering at the container when passing it anywehere is useless?
I use this code:
<?=$this->navigation()->menu()->renderPartial(null, 'shared/menu.phtml')?>
you should pass true to the method $page->isActive(true) so that also functions in depth.
in your partial
foreach ($this->container as $page) {
$active = $page->isActive(true);
if (count($page->getPages())) {
foreach ($page->getPages() as $subPage) {
$active = $subPage->isActive(true);
echo '<div class="item">';
echo '<a class="'. ($active ? 'active' : '') .'" href="' . $this->baseUrl($subPage->getHref()) . '">' . $subPage->getLabel() . '</a>';
echo '</div>';
}
}
}
before the second foreach you could add a check if and when to show the submenu.
my 2 cent.
EDIT
try this:
$partial = array('partials/menu.phtml', 'default');
echo $this->navigation()->menu()
->setMinDepth(1)
->setMaxDepth(1)
->setRenderParents(false)
->setOnlyActiveBranch(true)
->setPartial($partial)
->render();
Came across this while searching for an answer to the same problem. Having looked through the code for Zend_View_Helper_Navigation_Menu, it doesn't look like any of the view helper options are passed through to the view partial, although I don't see why they couldn't be... (in ZF 1.12 take look a line 736 of Zend_View_Helper_Navigation_Menu, the only thing passed is the container itself, the options array could easily be passed along with it, or the container prefiltered, may be worth filing a feature request with ZF)
These options are purely a way of filtering the Zend_Navigation_Container for rendering with the default renderMenu method. As you say, it seems you can accomplish the same thing by first filtering the container and then passing it as the first argument of the renderPartial method
In your main view
Find the container of the submenu located in navigation config. Then echo this container using said partial.
$pages = $this->navigation()->findOneBy('label', 'Label of your submenu');
echo $this->navigation()->menu()->renderPartial($pages,module/partials/menu.phtml');
In the partial (module/partials/menu.phtml)
Customise. This example iterates over the top level pages of your chosen container.
foreach ($this->container as $page) {
echo $this->navigation()->menu()->htmlify($page) . PHP_EOL;
}

Displaying images in atom feed

I have problems with displaying images in atom file. It doesn't include images in feed in google reader, opera or firefox.
As a starting point I did everything like in Listing 6. at [An overview of the Atom 1.0 Syndication Format] But it doesn't work.
Update
It is not problem with hotlink protected images. Described here: How to display item photo in atom feed?
Later I changed feed according to description posted here.
I added:
<media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="path_to_image.jpg" />
But still it doesn't work
I had the same problem when trying to include images as enclosure, but it seemed that the easiest way for me was to include the image with the normal img tag to the html content.
(It's also wrapped in CDATA, which might affect the way Google Reader handles the content. I haven't tried without.)
The following example works for me to make atom feed images visible in Google Reader:
<content type="html">
<![CDATA[
<a href="http://test.lvh.me:3000/listings/341-test-pics?locale=en">
<img alt="test_pic" src="http://test.lvh.me:3000/system/images/20/medium/test_pic.jpg?1343246102" />
</a>
]]>
</content>
Wordpress uses the metafield enclosure to set the medias. This is the correct tag according to RSS specification. I have seen people suggest using media:content but if using that make sure to set the XML namespace for it.
Unfortunately due to some dodgy Wordpress code you can not set this dynamically. (Wordpress gets all metafields and then loops through them instead of calling the enclosure directly)
You can set the enclosure on save post. It should be an array with entries of the form "$url\n$length\n$type"
If you want to add the enclosure tags yourself you can do the following:
RSS
add_action( 'rss2_item', 'hughie_rss2_item_enclosure' );
function hughie_rss2_item_enclosure():void
{
$id = get_post_thumbnail_id();
$url = wp_get_attachment_url($id);
$length = filesize(get_attached_file($id));
$type = get_post_mime_type($id);
echo apply_filters( 'rss_enclosure', '<enclosure url="' . esc_url( $url ) . '" length="' . absint( $length ) . '" type="' . esc_attr( $type ) . '" />' . "\n" );
}
ATOM:
add_action( 'atom_entry', 'hughie_atom_entry_enclosure' );
function hughie_atom_entry_enclosure():void
{
$id = get_post_thumbnail_id();
$url = wp_get_attachment_url($id);
$length = filesize(get_attached_file($id));
$type = get_post_mime_type($id);
echo apply_filters( 'atom_enclosure', '<link rel="enclosure" href="' . esc_url( $url ) . '" length="' . absint( $length ) . '" type="' . esc_attr( $type ) . '" />' . "\n" );
}
The only way I found to set the enclosure dynamically is short-circuiting the get_metadata call. You can add checks to make sure that you are in a feed or even the check the stacktrace to make sure.
add_filter('get_post_metadata', 'hughie_get_post_metadata', 10, 5 );
function hughie_get_post_metadata($value, int $object_id, string $meta_key, bool $single, string $meta_type)
{
if (is_feed() && $meta_key === '') {
$backtrace = debug_backtrace();
if (isset($backtrace[7]['function']) && ( $backtrace[7]['function'] === 'rss_enclosure' || $backtrace[7]['function'] === 'atom_enclosure' ) ) {
if (!isset($value['enclosure'])) {
$value['enclosure'] = [];
}
$id = get_post_thumbnail_id();
$url = wp_get_attachment_url($id);
$length = filesize(get_attached_file($id));
$type = get_post_mime_type($id);
$value['enclosure'][] = "$url\n$length\n$type";
}
}
return $value;
}

Access Form values in my Symfony executeAction backend

So one of my pages consists of a quiz form that has several questions of type multiple choice, the choices are specified as radio buttons. I have been scanning the Symfony documentation to find out how to access form field values inputted by the user. Thing is, this isn;t a doctrine or propel based form, and neither do I require the values to be stored in the database, hence executing a $form->save() makes little sense to me. But I do require access to specific values of my form in my backend once the user hits submit.
Most of Symfony documentation that i have run into doesn't necessarily explain how this can be done. I would assume it would be something to the effect of :
$request->getParameter( 'radio_choices_id selected value ').
Thanks to all who read this and Cheers to the ones who respond to it :)
Parijat
Hm, it is very simple if I understand your question right)
For widget:
$this->widgetSchema['name'] = new sfWidgetFormChoice(array('choices' => array('ch_1', 'ch_2')));
Ok,in action:
$this->form = new FaqContactForm();
if ($request->isMethod('post')) {
$this->form->bind($request->getParameter($this->form->getName()));
if ($this->form->isValid()) {
$your_val=$this->form->getValue('name');
//or
$your_val=$this->form['name']->getValue());
}
}
In backend in protected function processForm(sfWebRequest $request, sfForm $form)
you have
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
if ($form->isValid())
{
$notice = $form->getObject()->isNew() ? 'The item was created successfully.' : 'The item was updated successfully.';
try {
$product = $form->save();
} catch (Doctrine_Validator_Exception $e) {
$errorStack = $form->getObject()->getErrorStack();
$message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ? 's' : null) . " with validation errors: ";
foreach ($errorStack as $field => $errors) {
$message .= "$field (" . implode(", ", $errors) . "), ";
}
$message = trim($message, ', ');
$this->getUser()->setFlash('error', $message);
return sfView::SUCCESS;
}
Before $product = $form->save(); try
$your_val=$form->getValue('name');
//or
$your_val=$form['name']->getValue());