Getting Gravity Forms field attributes by label text - gravityforms

I am working on a function to find a field from any form based on the label text. I'd like to return different attributes of the field so that I can use them later.
Originally, I just needed the value of the field, so I used the work here to return the value of a field based on the label:
function itsg_get_value_by_label( $form, $entry, $label ) {
foreach ( $form['fields'] as $field ) {
$lead_key = $field->label;
if ( strToLower( $lead_key ) == strToLower( $label ) ) {
return $entry[ $field->id ];
}
}
return false;
}
I get my value by setting a variable and passing in the field label that I'm looking for:
$mobile_phone = itsg_get_value_by_label( $form, $entry, "Mobile Phone" );
Later on, as I continued to work on my solution, I found that I also needed to find those fields and return the ID. Initially, I wrote the same function and just returned the ID, but I'd like to make the solution more efficient by rewriting the function to return multiple field attributes in an array, as such:
function get_field_atts_by_label( $form, $entry, $label ) {
foreach ( $form['fields'] as $field ) {
$lead_key = $field->label;
if ( strToLower( $lead_key ) == strToLower( $label ) ) {
$field_atts = array(
'value' => $entry[ $field->id ],
'id' => $field->id,
);
return $field_atts;
}
}
return false;
}
My problem now is that I am not quite sure how to retrieve the specific attributes from my function and set them to a variable.

Well, I'll go ahead and answer my own question. Such a simple solution to this one. Had a momentary brain fart.
$mobile_phone = get_field_atts_by_label( $form, $entry, "Mobile Phone" );
$mobile_phone_id = $mobile_phone['id'];
$mobile_phone_value = $mobile_phone['value'];

Related

Search filter not working with custom search

I have a search() function in my model and I have messed around a bit with it in order to filter my results with some custom filters. So in my model I have this:
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$startdate='';
$enddate='';
if ($this->year!=''){
$year=explode('-', $this->year);
$date=DateTime::createFromFormat('Y', $year[0])->format('d/m/Y');
$startdate = General::getSeasonStartDate($date);
$enddate = General::getSeasonEndDate($date);
}
$criteria=new CDbCriteria;
$criteria->with=array(
'contracts'=>array(
'select'=>'contracts.contractdate',
'together'=>true
),
'schoolstudents' => array(
'together' => true,
'select' => false,
),
'schoolstudents.school'
);
//$criteria->order='lastname, firstname, fathername, mothername';
if (Yii::app()->user->CompanyID){
$criteria->compare('school.companyid',Yii::app()->user->CompanyID);
}
if(Yii::app()->user->SchoolID){
$criteria->compare('schoolstudents.schoolid',Yii::app()->user->SchoolID);
}
$criteria->compare('schoolstudents.schoolid', $this->schoolid);
//$criteria->compare('studentid',$this->studentid);
$criteria->compare('lastname',$this->lastname,true);
$criteria->compare('firstname',$this->firstname,true);
$criteria->compare('fathername',$this->fathername,true);
$criteria->compare('telephone1',$this->telephone1,true);
$criteria->compare('telephone2',$this->telephone2,true);
$criteria->compare('cellphone1',$this->cellphone1,true);
$criteria->compare('cellphone2',$this->cellphone2,true);
$criteria->compare('email1',$this->email1,true);
$criteria->compare('email2',$this->email2,true);
if($this->year!=''){
if ($startdate && $enddate){
$from = DateTime::createFromFormat('d/m/Y', $startdate)->format('Y-m-d');
$to = DateTime::createFromFormat('d/m/Y', $enddate)->format('Y-m-d');
if ($this->filter=='R'){
$criteria->addBetweenCondition('contractdate',$from, $to, 'AND');
}
else {
$criteria->addBetweenCondition('schoolstudents.createddate',$from, $to, 'AND');
}
}
} else {
if ($this->filter=='R'){
$criteria->addCondition('contracts.studentid');
} else {
$criteria->addCondition('schoolstudents.studentid');
}
}
if(isset($this->birthdate))
{
if($this->birthdate!='') {
$criteria->addCondition('year(birthdate)=:birthdate');
$criteria->params=CMap::mergeArray($criteria->params,array(
':birthdate'=>$this->birthdate,
)
);
}
}
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'lastname asc',
),
'pagination'=>array(
'pageSize'=>50,
),
));
}
my controller looks like this:
public function actionAdmin()
{
$model=new Student('search');
$model->unsetAttributes();
$y=date('Y');
$y1=date('Y',strtotime($y.'+1 year'));
$test=$y.'-'.$y1;
$model->year=$test;
$model->filter='A';
if (isset($_GET['Student']['year'])){
$model->year=($_GET['Student']['year']);
}
if (isset($_GET['Student']['filter'])){
$model->filter=$_GET['Student']['filter'];
}
if(isset($_GET['Student']))
$model->attributes=$_GET['Student'];
$this->render('admin',array(
'model'=>$model,
));
}
and my problem is that when I use the search filters provided by Yii they don't work. I don't get an error. They don't return anything. If I remove from search() the extra conditions I've added then the filters work fine. But then I can't use my custom filters. Anybody has any idea how to solve this?Thanks in advance!
Never mind I solved it. I changed my controller to this:
public function actionAdmin()
{
$model=new Student('search');
$model->unsetAttributes();
$y=date('Y');
$y1=date('Y',strtotime($y.'+1 year'));
$test=$y.'-'.$y1;
if (isset($_GET['Student']['year'])){
$model->year=$_GET['Student']['year'];
}
if (isset($_GET['Student']['filter'])){
$model->filter=$_GET['Student']['filter'];
}
if(isset($_GET['Student'])){
$model->attributes=$_GET['Student'];
} else{
//for custom & ajax filters to work together
$model->year=$test;
$model->filter='A';
}
$this->render('admin',array(
'model'=>$model,
));

How to clear the recent searched keywords display on website - Recent Searches Widget

I have installed a plugin from this question -->
Show most recent search terms in wordpress. I have the plugin working on my site, but i would like to ask that, how to clear the recent searched keywords that displaying on my website. I am running out of idea how to make it happen.
As you can see the result from my site: www.ncc.my. There are now 10 keywords on top of search box. I want to clear all the keyword. I have searched over the google but yet to get the answer. Here is the php code of the widget. See if you can get the solution to clear the keywords. Thanks!
<?php
/*
Plugin Name: Recent Searches Widget
Plugin URI: http://www.poradnik-webmastera.com/projekty/recent_searches_widget/
Description: Shows recent searches in a sidebar widget.
Author: Daniel Frużyński
Version: 1.2
Author URI: http://www.poradnik-webmastera.com/
Text Domain: recent-searches-widget
*/
/* Copyright 2009-2010 Daniel Frużyński (email : daniel [A-T] poradnik-webmastera.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
if ( !class_exists( 'RecentSearchesWidget' ) ) {
class RecentSearchesWidget {
// Constructor
function RecentSearchesWidget() {
// Initialize plugin
add_action( 'init', array( &$this, 'init' ) );
// Page load
add_action( 'template_redirect', array( &$this, 'template_redirect' ) );
// Widgets initialization
add_action( 'widgets_init', array( &$this, 'widgets_init' ) );
}
// Plugin initialization
function init() {
load_plugin_textdomain( 'recent-searches-widget', false, dirname( plugin_basename( __FILE__ ) ) . '/lang' );
}
// Page load
function template_redirect() {
if ( is_search() ) {
// Store search term
$query = $this->strtolower( trim( get_search_query() ) );
$options = get_option( 'recent_searches_widget' );
if ( !is_array( $options ) ) {
$options = $this->get_default_options();
}
$max = $options['max'];
$data = get_option( 'recent_searches_widget_data', array() );
if ( !is_array( $data ) ) {
if ( isset( $options['data'] ) ) {
$data = $options['data'];
unset( $options['data'] );
update_option( 'recent_searches_widget', $options );
}
if ( !is_array( $data ) ) {
$data = array();
}
}
$pos = array_search( $query, $data );
if ( $pos !== false ) {
if ( $pos != 0 ) {
$data = array_merge( array_slice( $data, 0, $pos ),
array( $query ), array_slice( $data, $pos + 1 ) );
}
} else {
array_unshift( $data, $query );
if ( count( $data ) > $max ) {
array_pop( $data );
}
}
update_option( 'recent_searches_widget_data', $data );
}
}
// Widgets initialization
function widgets_init() {
$widget_ops = array(
'classname' => 'widget_rsw',
'description' => __('Shows recent searches', 'recent-searches-widget'),
);
wp_register_sidebar_widget( 'recentsearcheswidget', __('Recent Searches', 'recent-searches-widget'),
array( &$this, 'widget_rsw' ), $widget_ops );
wp_register_widget_control( 'recentsearcheswidget', __('Recent Searches', 'recent-searches-widget'),
array( &$this, 'widget_rsw_control' ) );
}
function widget_rsw( $args ) {
extract( $args );
$title = isset( $options['title'] ) ? $options['title'] : '';
$title = apply_filters( 'widget_title', $title );
if ( empty($title) )
$title = ' ';
echo $before_widget . $before_title . $title . $after_title, "\n";
$this->show_recent_searches( "<ul>\n<li>", "</li>\n</ul>", "</li>\n<li>" );
echo $after_widget;
}
function show_recent_searches( $before_list, $after_list, $between_items ) {
$options = get_option( 'recent_searches_widget' );
if ( !is_array( $options ) ) {
$options = $this->get_default_options();
}
$data = get_option( 'recent_searches_widget_data' );
if ( !is_array( $data ) ) {
if ( isset( $options['data'] ) ) {
$data = $options['data'];
}
if ( !is_array( $data ) ) {
$data = array();
}
}
if ( count( $data ) > 0 ) {
echo $before_list;
$first = true;
foreach ( $data as $search ) {
if ( $first ) {
$first = false;
} else {
echo $between_items;
}
echo '<a href="', get_search_link( $search ), '"';
if ( $options['nofollow'] ) {
echo ' rel="nofollow"';
}
echo '>', wp_specialchars( $search ), '</a>';
}
echo $after_list, "\n";
} else {
_e('No searches yet', 'recent-searches-widget');
}
}
function widget_rsw_control() {
$options = $newoptions = get_option('recent_searches_widget', array() );
if ( count( $options ) == 0 ) {
$options = $this->get_default_options();
update_option( 'recent_searches_widget', $options );
}
if ( isset( $_POST['rsw-submit'] ) ) {
$options['title'] = strip_tags( stripslashes( $_POST['rsw-title'] ) );
$options['max'] = (int)( $_POST['rsw-max'] );
$options['nofollow'] = isset( $_POST['rsw-nofollow'] );
if ( count( $options['data'] ) > $options['max'] ) {
$options['data'] = array_slice( $options['data'], 0, $options['max'] );
}
update_option( 'recent_searches_widget', $options );
}
$title = attribute_escape( $options['title'] );
$max = attribute_escape( $options['max'] );
$nofollow = $options['nofollow'];
?>
<p><label for="rsw-title"><?php _e('Title:', 'recent-searches-widget'); ?> <input class="widefat" id="rsw-title" name="rsw-title" type="text" value="<?php echo $title; ?>" /></label></p>
<p><label for="rsw-max"><?php _e('Max searches:', 'recent-searches-widget'); ?> <input id="rsw-max" name="rsw-max" type="text" size="3" maxlength="5" value="<?php echo $max; ?>" /></label></p>
<p><label for="rsw-nofollow"><?php _e('Add <code>rel="nofollow"</code> to links:', 'recent-searches-widget'); ?> <input id="rsw-nofollow" name="rsw-nofollow" type="checkbox" value="yes" <?php checked( $nofollow, true ); ?>" /></label></p>
<input type="hidden" id="rsw-submit" name="rsw-submit" value="1" />
<?php
}
// Make string lowercase
function strtolower( $str ) {
if ( function_exists( 'mb_strtolower' ) ) {
return mb_strtolower( $str );
} else {
return strtolower( $str );
}
}
function get_default_options() {
return array(
'title' => '',
'max' => 4,
'nofollow' => true,
);
}
}
// Add functions from WP2.8 for previous WP versions
if ( !function_exists( 'esc_html' ) ) {
function esc_html( $text ) {
return wp_specialchars( $text );
}
}
if ( !function_exists( 'esc_attr' ) ) {
function esc_attr( $text ) {
return attribute_escape( $text );
}
}
// Add functions from WP3.0 for previous WP versions
if ( !function_exists( 'get_search_link' ) ) {
function get_search_link( $query = '' ) {
global $wp_rewrite;
if ( empty($query) )
$search = get_search_query();
else
$search = stripslashes($query);
$permastruct = $wp_rewrite->get_search_permastruct();
if ( empty( $permastruct ) ) {
$link = home_url('?s=' . urlencode($search) );
} else {
$search = urlencode($search);
$search = str_replace('%2F', '/', $search); // %2F(/) is not valid within a URL, send it unencoded.
$link = str_replace( '%search%', $search, $permastruct );
$link = trailingslashit( get_option( 'home' ) ) . user_trailingslashit( $link, 'search' );
}
return apply_filters( 'search_link', $link, $search );
}
}
$wp_recent_searches_widget = new RecentSearchesWidget();
// Show recent searches anywhere in the theme
function rsw_show_recent_searches( $before_list = "<ul>\n<li>", $after_list = "</li>\n</ul>", $between_items = "</li>\n<li>" ) {
global $wp_recent_searches_widget;
$wp_recent_searches_widget->show_recent_searches( $before_list, $after_list, $between_items );
}
} // END
?>
I can't see which part is for clearing up the keywords. Any suggestion? Thanks!
Updated part:
After the clearing history issue solved, this is the next issue i got.
function get_default_options() {
return array(
'title' => '',
'max' => 4, <---it was originally set to 10
'nofollow' => true,
);
}
}
I have set the searched keywords to "4" which was originally set as 10, it should work and display only maximum 4 keywords by right. But, i don't know why the setting seems to follow the very first time i use this plugin. No matter how i tried to set from 0 to 5, the setting never take effect and the keywords there are still displaying as maximum 10 searches. Need help in this!
Any solution?
I found an "archaic" way to do it.
If you search for "store" in the script", at the end of it you'll find the string
update_option( 'recent_searches_widget_data', $data );
If you set $data to 0 (e.g. $data=0;)right before this line and then you try to search something, you'll be able to delete the search history.
Remember to delete the line where you set $data to 0, otherwise the plugin won't start to work again
Edit:
Sorry for the late response, but I have the answers for your question (and also another way to do the previous point).
What I understood is that from the script you can't change after the initialisation the number of elements that have to be shown. When does this happen? When you install the plugin. So you should unzip the folder, change the number of elements in the .php file, zip the folder and install again the plugin.
Not so tricky, but quite long.
Now, the good news.
I don't know if you have ever managed with the database that is behind wp, but there is a table (wp_options) where many part of code that wordpress uses are stored.
Usually here you can also find the data that the plugins set up.
And here we go: in that table there are two rows, called recent_searches_widget and recent_searches_widget_data.
In the first you can find the setting for the number of elements to be shown (its the i:10; that is set by default, if you haven't changed the script yet), in the other you can find the previous searches (and, if you want to delete them, you just need to change the value of the row to 0).

Change currency position according to currency in wordpress

Googled and searched but I couldn't find what I was looking for.
I am building a woocommerce website which has 2 currencies: KRW and USD.
I have two buttons which switch between these currencies.
When KRW is selected, price display 10,000W and when USD is selected, it displays 100$.
What I want is to display $100 when USD is selected.
I tried in my functions.php:
add_filter('woocommerce_price_format','change_currency_pos');
function change_currency_pos( $currency_pos, $currency ) {
switch( $currency ) {
case 'USD': $currency_pos = '%1$s%2$s'; break;
case 'KRW': $currency_pos = '%2$s%1$s'; break;
}
return $currency_pos;
}
also tried:
function change_currency_pos() {
$currency_pos = get_option('woocommerece_currency');
switch($currency_pos) {
case 'USD': $format = '%1$s%2$s'; break;
case 'KRW': $format = '%2$s%1$s'; break;
}
return $currency_pos;
}
add_filter('woocommerce_price_format','change_currency_pos');
Both didn't work. :(
Can somebody help please. Thank you.
This is just a guess since I don't know what plugin you are using or how it works. I am going to assume that it adds a $_GET variable named currency to the end of your URL. www.example.com&currency=KRW But idea is that you set a value for the woocommerce_currency_pos option based on some data provided by the currency plugin.
add_filter( 'pre_option_woocommerce_currency_pos', 'change_currency_position' );
function change_currency_position(){
if( ! isset( $_GET['currency'] ) {
return false;
}
if ( 'USD' == $_GET['currency'] ){
return 'left';
} elseif ( 'KRW' == $_GET['currency'] ){
return 'right';
}
}
Alternatively, I could assume that "right" is the default currency position. And that you only need to filter the option in the instance where the site is displayed in USD-mode. In which case you would only need the following
add_filter( 'pre_option_woocommerce_currency_pos', 'change_currency_position' );
function change_currency_position(){
if( isset( $_GET['currency'] && 'USD' == $_GET['currency'] ){
return 'left';
}
}
For woocommerce_price_format to work you need to set the format like this
add_filter('woocommerce_price_format', 'woo_custom_format_position', 999, 2);
function woo_custom_format_position($format, $currency_pos)
{
/*'left':$format = '%1$s%2$s';
'right':$format = '%2$s%1$s';
'left_space':$format = '%1$s %2$s';
'right_space':$format = '%2$s %1$s';
*/
$format = '%1$s%2$s';//Change your position
return $format;
}
For some strange reason the 'position' setting wasn't working for EUR currency. I had to add this to my functions.php in order to fix it:
add_filter('woocommerce_price_format', 'woo_custom_format_position', 999, 2);
function woo_custom_format_position($format, $currency_pos)
{
/*'left':$format = '%1$s%2$s';
'right':$format = '%2$s%1$s';
'left_space':$format = '%1$s %2$s';
'right_space':$format = '%2$s %1$s';
*/
switch ($currency_pos) {
case 'left':
return '%1$s%2$s';
case 'right':
return '%2$s%1$s';
case 'left_space':
return '%1$s %2$s';
case 'right_space':
return '%2$s %1$s';
};
}
Now it actually uses the position chosen in the settings.
Hope it helps somebody!

yii cgridview export into excel not working on pagination

my code export into excel works fine, 1 to 10 rows export if I filters rows that my code export filtered rows as my criteria. If I click to next page e.g 11 to 20 and then click on export button, export only first page 1 to 10 rows.
in my admin view export button code:
<div id='menub'><?php $this->widget('zii.widgets.CMenu', array(
'encodeLabel'=>false,
'htmlOptions'=>array(
'class'=>'actions'),
'items'=>array(
array(
'label'=>'<img align="absmiddle" alt = "'.Yii::t('internationalization','Export'). '" src = "'.Yii::app()->request->baseUrl.'/images/export.jpg" />',
//'label'=>'Export',
'url'=>array('expenses/excel'),
),
),
));
above link call to excel method in expenses controller.
code in my controller:
public function actionExcel() {
$issueDataProvider = $_SESSION['report-excel'];
$i = 0;
$data = array();
//fix column header.
//Could have used something like this - $data[]=array_keys($issueDataProvider->data[0]->attributes);.
//But that would return all attributes which i do not want
//$data[]=array_keys($issueDataProvider->data[0]->attributes);
$data[$i]['expenses_type_id'] = 'Type';
$data[$i]['amount'] = 'Amount';
$data[$i]['exp_date'] = 'Date';
$data[$i]['description'] = 'Description';
$i++;
//populate data array with the required data elements
foreach($issueDataProvider->data as $issue)
{
$data[$i]['expenses_type_id'] = $issue->expensesType->name;
$data[$i]['amount'] = $issue['amount'];
$data[$i]['exp_date'] = $issue['exp_date'];
$data[$i]['description'] = $issue['description'];
$i++;
}
Yii::import('application.extensions.phpexcel.JPhpExcel');
$xls = new JPhpExcel('UTF-8', false, 'test');
$xls->addArray($data);
$xls->generateXML('test_file');
}
I save data in
$_SESSION['report-excel']
and in my Model:
public function getSearchCriteria()
{
$criteria=new CDbCriteria;
if(!empty($this->from_date) && empty($this->to_date))
{
$criteria->condition = "exp_date >= '$this->from_date'"; // date is database date column field
}elseif(!empty($this->to_date) && empty($this->from_date))
{
$criteria->condition = "exp_date <= '$this->to_date'";
}elseif(!empty($this->to_date) && !empty($this->from_date))
{
$criteria->condition = "exp_date >= '$this->from_date' and exp_date <= '$this->to_date'";
}
$criteria->with = 'expensesType';
$criteria->join = 'LEFT JOIN expenses_type p ON t.expenses_type_id = p.id';
//s$criteria->compare('id',$this->id,true);
$criteria->compare('p.name',$this->expenses_type_id,true);
$criteria->compare('amount',$this->amount,true);
$criteria->compare('exp_date',$this->exp_date,true);
$criteria->compare('description',$this->description,true);
$criteria->order ='exp_date DESC';
return $criteria;
}
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$data = new CActiveDataProvider(get_class($this), array(
'pagination'=>array('pageSize'=> Yii::app()->user->getState('pageSize',
Yii::app()->params['defaultPageSize']),),
'criteria'=>$this->getSearchCriteria(),
));
$_SESSION['report-excel']=$data;
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$this->getSearchCriteria(),
));
every thing is works fine but on pagination.
kindly help.
CActiveDataProvider holds a set of items(all).So when you call actionExcel() the $page param is lost. So when you do actionAdmin() in your controller or search() in your model save your $_GET['page'] to an other session value. then set it when you do actionExcel().
$_GET['page'] = $_SESSION['your_session_page_value'];
Hope this helps
Best Regards

SubSonic How to provide a column name in a generic method

Using SubSonic3, I have this generic method (thanks to linq guy, James Curran):
public List<T> GetFromList<T>( List<Guid> _IDs,
Func<T, Guid> GetID,
Func<IQueryable<T>> GetAll )
where T : class, IActiveRecord
{
List<T> rc = null;
var Results =
from item in GetAll( )
where ( _IDs as IEnumerable<Guid> ).Contains( GetID( item ) )
select item;
rc = Results.ToList<T>( );
return rc;
}
It is called with something like
List<Job> jresults = GetFromList( IDList,
item => item.JobID,
( ) => Job.All( ) );
Where IDList is a List of guids that are keys to the table.
When not generic, the linq looks like this and works perfectly. I was quite impressed that SubSonic's linq provider could take this code and turn it into SELECT * FROM Job WHERE JobID IN (a, b, c):
var Results =
from item in Job.All( )
where ( _IDs as IEnumerable<Guid> ).Contains( item.JobID )
select item;
I want to be able to call this method on tables other than Job, with keys other than JobID. The GetAll Func works because it returns the same IQueryable that Job.All( ) does, but GetID throws a run-time exception, "LINQ expression node of type Invoke is not supported". GetID returns a value, but what I really need from it is something that Contains( item.JobID) would recognize as a column name and that the "where" syntax would accept. (I don't show it here, but I have the same problem with orderby.)
Is that possible, with what you know of SubSonic3?
My solution was to pass in the expression that Where needed:
public List<T> GetFromList( List<Guid> _IDs,
Func<IQueryable<T>> GetAll,
Expression<Func<T, bool>> _where )
where T : class, U, IActiveRecord
{
List<T> rc = new List<T>( );
if ( 0 < _IDs.Count )
{
if ( MAX_ITEMS > _IDs.Count )
{
var Results = GetAll( ).Where( _where );
rc = Results.ToList( );
}
else
{
var Results =
from id in _IDs
join item in GetAll( ) on id equals item.KeyValue( )
select item;
rc = Results.ToList( );
}
}
return rc;
}
called by
rc = GetFromList(
IDList,
( ) => Job.All( ),
( item => ( IDList as IEnumerable<Guid> ).Contains( item.JobID ) ) );

Resources