Hook::exec is not working for a particular module - prestashop-1.6

I am facing an issue regarding the hook::exec in my prestashop application, where module and hook method is installed properly. But when I tried to execute this module, it return false. Kindly suggest me. Module and hook method is showing in "Modules and Services / Positions" as well as ps_hook table in database.
Module base file is defined as :
public function __construct()
{
$this->name = 'callback';
$this->tab = 'front_office_features';
$this->version = '1.0';
$this->author = 'Amit Jha';
$this->need_instance = 0;
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l( 'Call Back' );
$this->description = $this->l( '....' );
$this->confirmUninstall = $this->l( 'Are you sure you want to uninstall? .... ' );
}
And Install method is as below:
if ( parent::install() && $this->registerHook( 'displayCallBack' ) && $this->registerHook( 'displayHeader' ) && $this->registerHook( 'displayCallBackCart' ) && $this->registerHook( 'displayCallBackLinkOnCartPopup' ) && $this->registerHook( 'displayCallBackLinkOnCartPopupWishlist' ) ) {
if ( !$this->alterTable( 'add' ) ) {
return false;
}
return true;
}
Hook Method:
public function hookDisplayCallBack( $params )
{
$results = CallBackServiceCore::searchDetail();
if ( count( $results ) <= 0 ) {
return;
}
foreach ( $results as $item ) {
$this->context->smarty->assign( array(
'description_text' => $item["description_text"],
'recall_promise' => $item["recall_promise"]
) );
}
$arrDate = $this->getCallingTime();
$this->context->smarty->assign( array(
'arrTimeList' => $arrDate,
'product_id' => $params["product"]->id,
'product_name' => $params["product"]->name,
'category' => $params["product"]->category
)
);
return $this->display( __file__, 'display.tpl' );
}
Please suggest where I made mistake.

Related

GravityForms Dynamic Confirmation Redirects

I have set up a gravity form with a single line text field. I am using it to check for zip codes and cities. If someone types in the correct zip code it will redirect to a specific page. Also if someone types in a zip code or city and there is no matching value it will also redirect to a certain page. I have tried this code. But I can not seem to get it to work correctly. It works if I have one number but if I add multiple numbers separated by a comma it does not work. Please help if possible.
<?php
function de_gforms_confirmation_dynamic_redirect( $confirmation, $form, $entry, $ajax ) {
if ( $form['id'] == '38' ) {
if ( $entry['1'] == '89103,80205,91030' ) {
$confirmation = array( 'redirect' => 'https://google.com' );
} else if ( $entry['1'] == '90210,89554,90454' ) {
$confirmation = array( 'redirect' => 'https://yahoo.com' );
} else if ( $entry['1'] == '56678,89004,78896' ) {
$confirmation = array( 'redirect' => 'https://test.com' );
}
}
return $confirmation;
}
add_filter( 'gform_confirmation', 'de_gforms_confirmation_dynamic_redirect', 10, 4 );
?>
You need to use the or operator "||" instead of the array of zipcodes
<?php
function de_gforms_confirmation_dynamic_redirect( $confirmation, $form, $entry, $ajax ) {
if ( $form['id'] == '38' ) {
if ( $entry['1'] == '89103' || $entry['1'] == '80205' || $entry['1'] == '91030' ) {
$confirmation = array( 'redirect' => 'https://google.com' );
} else if ( $entry['1'] == '90210' || $entry['1'] == '89554' || $entry['1'] == '90454' ) {
$confirmation = array( 'redirect' => 'https://yahoo.com' );
} else if ( $entry['1'] == '56678' || $entry['1'] == '89004' || $entry['1'] == '78896' ) {
$confirmation = array( 'redirect' => 'https://test.com' );
}
}
return $confirmation;
}
There's a lot of ways you could do this. I would probably try to turn your zip codes/redirect into an associative array (https://wtools.io/convert-csv-to-php-array) that you could loop through like this:
function de_gforms_confirmation_dynamic_redirect( $confirmation, $form, $entry, $ajax ) {
$zip_group = array("1234","2345","3456");
$count_group = count($zip_group);
for($i=0;$i<$count_group;$i++){
$redirect[$i]='https://google.com';
}
$zip_condition = array_combine( $zip_group , $redirect );
if( $form['id'] == '38' ) {
foreach($zip_condition as $zip => $condition) {
if ( $entry['1'] == $zip ) {
$confirmation = array( 'redirect' => $condition );
}
}
}
return $confirmation;
}

How to alter woocommerce widget filter by attribute widget?

I use the default Woocommerce widget "Filter by attribute" and I would like to prepend the name of each attributes.
But I don't find any hook on it
Do you know how to achieve this ?
What about extending its class to override the widget?
in your functions.php, add this class, you can then change the elements or do conditional statements depending on what you need.
/**
* Layered nav widget
*
* #package WooCommerce/Widgets
* #version 2.6.0
*/
/**
* Widget layered nav class.
*/
class The_New_Attribute_Widget extends WC_Widget_Layered_Nav {
/**
* Constructor.
*/
public function __construct() {
$this->widget_cssclass = 'woocommerce widget_layered_nav woocommerce-widget-layered-nav';
$this->widget_description = __( 'Display a list of attributes to filter products in your store.', 'woocommerce' );
$this->widget_id = 'woocommerce_layered_nav';
$this->widget_name = __( 'Filter Products by Attribute', 'woocommerce' );
parent::__construct();
}
/**
* Updates a particular instance of a widget.
*
* #see WP_Widget->update
*
* #param array $new_instance New Instance.
* #param array $old_instance Old Instance.
*
* #return array
*/
public function update( $new_instance, $old_instance ) {
$this->init_settings();
return parent::update( $new_instance, $old_instance );
}
/**
* Outputs the settings update form.
*
* #see WP_Widget->form
*
* #param array $instance Instance.
*/
public function form( $instance ) {
$this->init_settings();
parent::form( $instance );
}
/**
* Init settings after post types are registered.
*/
public function init_settings() {
$attribute_array = array();
$std_attribute = '';
$attribute_taxonomies = wc_get_attribute_taxonomies();
if ( ! empty( $attribute_taxonomies ) ) {
foreach ( $attribute_taxonomies as $tax ) {
if ( taxonomy_exists( wc_attribute_taxonomy_name( $tax->attribute_name ) ) ) {
$attribute_array[ $tax->attribute_name ] = $tax->attribute_name;
}
}
$std_attribute = current( $attribute_array );
}
$this->settings = array(
'title' => array(
'type' => 'text',
'std' => __( 'Filter by', 'woocommerce' ),
'label' => __( 'Title', 'woocommerce' ),
),
'attribute' => array(
'type' => 'select',
'std' => $std_attribute,
'label' => __( 'Attribute', 'woocommerce' ),
'options' => $attribute_array,
),
'display_type' => array(
'type' => 'select',
'std' => 'list',
'label' => __( 'Display type', 'woocommerce' ),
'options' => array(
'list' => __( 'List', 'woocommerce' ),
'dropdown' => __( 'Dropdown', 'woocommerce' ),
),
),
'query_type' => array(
'type' => 'select',
'std' => 'and',
'label' => __( 'Query type', 'woocommerce' ),
'options' => array(
'and' => __( 'AND', 'woocommerce' ),
'or' => __( 'OR', 'woocommerce' ),
),
),
);
}
/**
* Get this widgets taxonomy.
*
* #param array $instance Array of instance options.
* #return string
*/
protected function get_instance_taxonomy( $instance ) {
if ( isset( $instance['attribute'] ) ) {
return wc_attribute_taxonomy_name( $instance['attribute'] );
}
$attribute_taxonomies = wc_get_attribute_taxonomies();
if ( ! empty( $attribute_taxonomies ) ) {
foreach ( $attribute_taxonomies as $tax ) {
if ( taxonomy_exists( wc_attribute_taxonomy_name( $tax->attribute_name ) ) ) {
return wc_attribute_taxonomy_name( $tax->attribute_name );
}
}
}
return '';
}
/**
* Get this widgets query type.
*
* #param array $instance Array of instance options.
* #return string
*/
protected function get_instance_query_type( $instance ) {
return isset( $instance['query_type'] ) ? $instance['query_type'] : 'and';
}
/**
* Get this widgets display type.
*
* #param array $instance Array of instance options.
* #return string
*/
protected function get_instance_display_type( $instance ) {
return isset( $instance['display_type'] ) ? $instance['display_type'] : 'list';
}
/**
* Output widget.
*
* #see WP_Widget
*
* #param array $args Arguments.
* #param array $instance Instance.
*/
public function widget( $args, $instance ) {
if ( ! is_shop() && ! is_product_taxonomy() ) {
return;
}
$_chosen_attributes = WC_Query::get_layered_nav_chosen_attributes();
$taxonomy = $this->get_instance_taxonomy( $instance );
$query_type = $this->get_instance_query_type( $instance );
$display_type = $this->get_instance_display_type( $instance );
if ( ! taxonomy_exists( $taxonomy ) ) {
return;
}
$terms = get_terms( $taxonomy, array( 'hide_empty' => '1' ) );
if ( 0 === count( $terms ) ) {
return;
}
ob_start();
$this->widget_start( $args, $instance );
if ( 'dropdown' === $display_type ) {
wp_enqueue_script( 'selectWoo' );
wp_enqueue_style( 'select2' );
$found = $this->layered_nav_dropdown( $terms, $taxonomy, $query_type );
} else {
$found = $this->layered_nav_list( $terms, $taxonomy, $query_type );
}
$this->widget_end( $args );
// Force found when option is selected - do not force found on taxonomy attributes.
if ( ! is_tax() && is_array( $_chosen_attributes ) && array_key_exists( $taxonomy, $_chosen_attributes ) ) {
$found = true;
}
if ( ! $found ) {
ob_end_clean();
} else {
echo ob_get_clean(); // #codingStandardsIgnoreLine
}
}
/**
* Return the currently viewed taxonomy name.
*
* #return string
*/
protected function get_current_taxonomy() {
return is_tax() ? get_queried_object()->taxonomy : '';
}
/**
* Return the currently viewed term ID.
*
* #return int
*/
protected function get_current_term_id() {
return absint( is_tax() ? get_queried_object()->term_id : 0 );
}
/**
* Return the currently viewed term slug.
*
* #return int
*/
protected function get_current_term_slug() {
return absint( is_tax() ? get_queried_object()->slug : 0 );
}
/**
* Show dropdown layered nav.
*
* #param array $terms Terms.
* #param string $taxonomy Taxonomy.
* #param string $query_type Query Type.
* #return bool Will nav display?
*/
protected function layered_nav_dropdown( $terms, $taxonomy, $query_type ) {
global $wp;
$found = false;
if ( $taxonomy !== $this->get_current_taxonomy() ) {
$term_counts = $this->get_filtered_term_product_counts( wp_list_pluck( $terms, 'term_id' ), $taxonomy, $query_type );
$_chosen_attributes = WC_Query::get_layered_nav_chosen_attributes();
$taxonomy_filter_name = wc_attribute_taxonomy_slug( $taxonomy );
$taxonomy_label = wc_attribute_label( $taxonomy );
/* translators: %s: taxonomy name */
$any_label = apply_filters( 'woocommerce_layered_nav_any_label', sprintf( __( 'Any %s', 'woocommerce' ), $taxonomy_label ), $taxonomy_label, $taxonomy );
$multiple = 'or' === $query_type;
$current_values = isset( $_chosen_attributes[ $taxonomy ]['terms'] ) ? $_chosen_attributes[ $taxonomy ]['terms'] : array();
if ( '' === get_option( 'permalink_structure' ) ) {
$form_action = remove_query_arg( array( 'page', 'paged' ), add_query_arg( $wp->query_string, '', home_url( $wp->request ) ) );
} else {
$form_action = preg_replace( '%\/page/[0-9]+%', '', home_url( trailingslashit( $wp->request ) ) );
}
echo '<form method="get" action="' . esc_url( $form_action ) . '" class="woocommerce-widget-layered-nav-dropdown">';
echo '<select class="woocommerce-widget-layered-nav-dropdown dropdown_layered_nav_' . esc_attr( $taxonomy_filter_name ) . '"' . ( $multiple ? 'multiple="multiple"' : '' ) . '>';
echo '<option value="">' . esc_html( $any_label ) . '</option>';
foreach ( $terms as $term ) {
// If on a term page, skip that term in widget list.
if ( $term->term_id === $this->get_current_term_id() ) {
continue;
}
// Get count based on current view.
$option_is_set = in_array( $term->slug, $current_values, true );
$count = isset( $term_counts[ $term->term_id ] ) ? $term_counts[ $term->term_id ] : 0;
// Only show options with count > 0.
if ( 0 < $count ) {
$found = true;
} elseif ( 0 === $count && ! $option_is_set ) {
continue;
}
echo '<option value="' . esc_attr( urldecode( $term->slug ) ) . '" ' . selected( $option_is_set, true, false ) . '>' . esc_html( $term->name ) . '</option>';
}
echo '</select>';
if ( $multiple ) {
echo '<button class="woocommerce-widget-layered-nav-dropdown__submit" type="submit" value="' . esc_attr__( 'Apply', 'woocommerce' ) . '">' . esc_html__( 'Apply', 'woocommerce' ) . '</button>';
}
if ( 'or' === $query_type ) {
echo '<input type="hidden" name="query_type_' . esc_attr( $taxonomy_filter_name ) . '" value="or" />';
}
echo '<input type="hidden" name="filter_' . esc_attr( $taxonomy_filter_name ) . '" value="' . esc_attr( implode( ',', $current_values ) ) . '" />';
echo wc_query_string_form_fields( null, array( 'filter_' . $taxonomy_filter_name, 'query_type_' . $taxonomy_filter_name ), '', true ); // #codingStandardsIgnoreLine
echo '</form>';
wc_enqueue_js(
"
// Update value on change.
jQuery( '.dropdown_layered_nav_" . esc_js( $taxonomy_filter_name ) . "' ).change( function() {
var slug = jQuery( this ).val();
jQuery( ':input[name=\"filter_" . esc_js( $taxonomy_filter_name ) . "\"]' ).val( slug );
// Submit form on change if standard dropdown.
if ( ! jQuery( this ).attr( 'multiple' ) ) {
jQuery( this ).closest( 'form' ).submit();
}
});
// Use Select2 enhancement if possible
if ( jQuery().selectWoo ) {
var wc_layered_nav_select = function() {
jQuery( '.dropdown_layered_nav_" . esc_js( $taxonomy_filter_name ) . "' ).selectWoo( {
placeholder: decodeURIComponent('" . rawurlencode( (string) wp_specialchars_decode( $any_label ) ) . "'),
minimumResultsForSearch: 5,
width: '100%',
allowClear: " . ( $multiple ? 'false' : 'true' ) . ",
language: {
noResults: function() {
return '" . esc_js( _x( 'No matches found', 'enhanced select', 'woocommerce' ) ) . "';
}
}
} );
};
wc_layered_nav_select();
}
"
);
}
return $found;
}
/**
* Count products within certain terms, taking the main WP query into consideration.
*
* This query allows counts to be generated based on the viewed products, not all products.
*
* #param array $term_ids Term IDs.
* #param string $taxonomy Taxonomy.
* #param string $query_type Query Type.
* #return array
*/
protected function get_filtered_term_product_counts( $term_ids, $taxonomy, $query_type ) {
global $wpdb;
$tax_query = WC_Query::get_main_tax_query();
$meta_query = WC_Query::get_main_meta_query();
if ( 'or' === $query_type ) {
foreach ( $tax_query as $key => $query ) {
if ( is_array( $query ) && $taxonomy === $query['taxonomy'] ) {
unset( $tax_query[ $key ] );
}
}
}
$meta_query = new WP_Meta_Query( $meta_query );
$tax_query = new WP_Tax_Query( $tax_query );
$meta_query_sql = $meta_query->get_sql( 'post', $wpdb->posts, 'ID' );
$tax_query_sql = $tax_query->get_sql( $wpdb->posts, 'ID' );
// Generate query.
$query = array();
$query['select'] = "SELECT COUNT( DISTINCT {$wpdb->posts}.ID ) as term_count, terms.term_id as term_count_id";
$query['from'] = "FROM {$wpdb->posts}";
$query['join'] = "
INNER JOIN {$wpdb->term_relationships} AS term_relationships ON {$wpdb->posts}.ID = term_relationships.object_id
INNER JOIN {$wpdb->term_taxonomy} AS term_taxonomy USING( term_taxonomy_id )
INNER JOIN {$wpdb->terms} AS terms USING( term_id )
" . $tax_query_sql['join'] . $meta_query_sql['join'];
$query['where'] = "
WHERE {$wpdb->posts}.post_type IN ( 'product' )
AND {$wpdb->posts}.post_status = 'publish'"
. $tax_query_sql['where'] . $meta_query_sql['where'] .
'AND terms.term_id IN (' . implode( ',', array_map( 'absint', $term_ids ) ) . ')';
$search = WC_Query::get_main_search_query_sql();
if ( $search ) {
$query['where'] .= ' AND ' . $search;
}
$query['group_by'] = 'GROUP BY terms.term_id';
$query = apply_filters( 'woocommerce_get_filtered_term_product_counts_query', $query );
$query = implode( ' ', $query );
// We have a query - let's see if cached results of this query already exist.
$query_hash = md5( $query );
// Maybe store a transient of the count values.
$cache = apply_filters( 'woocommerce_layered_nav_count_maybe_cache', true );
if ( true === $cache ) {
$cached_counts = (array) get_transient( 'wc_layered_nav_counts_' . sanitize_title( $taxonomy ) );
} else {
$cached_counts = array();
}
if ( ! isset( $cached_counts[ $query_hash ] ) ) {
$results = $wpdb->get_results( $query, ARRAY_A ); // #codingStandardsIgnoreLine
$counts = array_map( 'absint', wp_list_pluck( $results, 'term_count', 'term_count_id' ) );
$cached_counts[ $query_hash ] = $counts;
if ( true === $cache ) {
set_transient( 'wc_layered_nav_counts_' . sanitize_title( $taxonomy ), $cached_counts, DAY_IN_SECONDS );
}
}
return array_map( 'absint', (array) $cached_counts[ $query_hash ] );
}
/**
* Show list based layered nav.
*
* #param array $terms Terms.
* #param string $taxonomy Taxonomy.
* #param string $query_type Query Type.
* #return bool Will nav display?
*/
protected function layered_nav_list( $terms, $taxonomy, $query_type ) {
// List display.
echo '<ul class="woocommerce-widget-layered-nav-list">';
$term_counts = $this->get_filtered_term_product_counts( wp_list_pluck( $terms, 'term_id' ), $taxonomy, $query_type );
$_chosen_attributes = WC_Query::get_layered_nav_chosen_attributes();
$found = false;
$base_link = $this->get_current_page_url();
foreach ( $terms as $term ) {
$current_values = isset( $_chosen_attributes[ $taxonomy ]['terms'] ) ? $_chosen_attributes[ $taxonomy ]['terms'] : array();
$option_is_set = in_array( $term->slug, $current_values, true );
$count = isset( $term_counts[ $term->term_id ] ) ? $term_counts[ $term->term_id ] : 0;
// Skip the term for the current archive.
if ( $this->get_current_term_id() === $term->term_id ) {
continue;
}
// Only show options with count > 0.
if ( 0 < $count ) {
$found = true;
} elseif ( 0 === $count && ! $option_is_set ) {
continue;
}
$filter_name = 'filter_' . wc_attribute_taxonomy_slug( $taxonomy );
$current_filter = isset( $_GET[ $filter_name ] ) ? explode( ',', wc_clean( wp_unslash( $_GET[ $filter_name ] ) ) ) : array(); // WPCS: input var ok, CSRF ok.
$current_filter = array_map( 'sanitize_title', $current_filter );
if ( ! in_array( $term->slug, $current_filter, true ) ) {
$current_filter[] = $term->slug;
}
$link = remove_query_arg( $filter_name, $base_link );
// Add current filters to URL.
foreach ( $current_filter as $key => $value ) {
// Exclude query arg for current term archive term.
if ( $value === $this->get_current_term_slug() ) {
unset( $current_filter[ $key ] );
}
// Exclude self so filter can be unset on click.
if ( $option_is_set && $value === $term->slug ) {
unset( $current_filter[ $key ] );
}
}
if ( ! empty( $current_filter ) ) {
asort( $current_filter );
$link = add_query_arg( $filter_name, implode( ',', $current_filter ), $link );
// Add Query type Arg to URL.
if ( 'or' === $query_type && ! ( 1 === count( $current_filter ) && $option_is_set ) ) {
$link = add_query_arg( 'query_type_' . wc_attribute_taxonomy_slug( $taxonomy ), 'or', $link );
}
$link = str_replace( '%2C', ',', $link );
}
if ( $count > 0 || $option_is_set ) {
$link = apply_filters( 'woocommerce_layered_nav_link', $link, $term, $taxonomy );
$term_html = '<a rel="nofollow" href="' . esc_url( $link ) . '">' . esc_html( $term->name ) . '</a>';
} else {
$link = false;
$term_html = '<span>' . esc_html( $term->name ) . '</span>';
}
$term_html .= ' ' . apply_filters( 'woocommerce_layered_nav_count', '<span class="count">(' . absint( $count ) . ')</span>', $count, $term );
echo '<li class="woocommerce-widget-layered-nav-list__item wc-layered-nav-term ' . ( $option_is_set ? 'woocommerce-widget-layered-nav-list__item--chosen chosen' : '' ) . '">';
echo apply_filters( 'woocommerce_layered_nav_term_html', $term_html, $term, $link, $count ); // WPCS: XSS ok.
echo '</li>';
}
echo '</ul>';
return $found;
}
}
then in your functions.php again, unregister the default attribute widget and register the new one above:
function your_widget_handler() {
unregister_widget( 'WC_Widget_Layered_Nav' ); //unregister
register_widget( 'The_New_Attribute_Widget' ); //Register the new class
}
add_action( 'widgets_init', 'your_widget_handler' );
I took a look at the source code and it seems that it's only possible if you chose "List" as the "Display type". If so, then there is a filter applied to the displayed elements:
apply_filters( 'woocommerce_layered_nav_term_html', $term_html, $term, $link, $count );
so in order to add custom filter, you can do:
function so_62519320_prepend_name( $term_html, $term, $link, $count ) {
// do stuff
return $some_modified_value;
}
add_filter( 'woocommerce_layered_nav_term_html', 'so_62519320_prepend_name', 10, 4 );
Unfortunately, if you chose "Dropdown" as the "Display type", then there are no filters applied and it seems that you can't modify labels. There's only
esc_html( $term->name )
used to display option labels, so the only way to change this is to change the value in the database.

How to hook tags to displayTopColumn in prestashop 1.6

Can somebody tell me how to display tags in TopColumn in prestashop 1.6?
I know that I must edit blogtags.php but I don't know how to do it - my PHP is too weak.
Of course I tried - now can I can hook tag in admin panel but not on website. What have I done?
.
.
.
function install()
{
$success = (parent::install() && $this->registerHook('header') && **$this->registerHook('displayTopColumn')** && Configuration::updateValue('BLOCKTAGS_NBR', 10));
if ($success)
.
.
.
public function hookdisplayTop($params)
{
return $this->hookdisplayTopColumn($params);
}
.
.
.
Full blogtags.php
if (!defined('_PS_VERSION_'))
exit;
define('BLOCKTAGS_MAX_LEVEL', 3);
class BlockTags extends Module
{
function __construct()
{
$this->name = 'blocktags';
$this->tab = 'front_office_features';
$this->version = '1.2.1';
$this->author = 'PrestaShop';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Tags block');
$this->description = $this->l('Adds a block containing your product tags.');
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
}
function install()
{
$success = (parent::install() && $this->registerHook('header') && $this->registerHook('displayTopColumn') && Configuration::updateValue('BLOCKTAGS_NBR', 10));
if ($success)
{
// Hook the module either on the left or right column
$theme = new Theme(Context::getContext()->shop->id_theme);
if ((!$theme->default_left_column || !$this->registerHook('leftColumn'))
&& (!$theme->default_right_column || !$this->registerHook('rightColumn'))
&& $this->registerHook('displayTopColumn'))
{
// If there are no colums implemented by the template, throw an error and uninstall the module
$this->_errors[] = $this->l('This module need to be hooked in a column and your theme does not implement one');
parent::uninstall();
return false;
}
}
return $success;
}
public function getContent()
{
$output = '';
if (Tools::isSubmit('submitBlockTags'))
{
if (!($tagsNbr = Tools::getValue('BLOCKTAGS_NBR')) || empty($tagsNbr))
$output .= $this->displayError($this->l('Please complete the "Displayed tags" field.'));
elseif ((int)($tagsNbr) == 0)
$output .= $this->displayError($this->l('Invalid number.'));
else
{
Configuration::updateValue('BLOCKTAGS_NBR', (int)$tagsNbr);
$output .= $this->displayConfirmation($this->l('Settings updated'));
}
}
return $output.$this->renderForm();
}
/**
* Returns module content for left column
*
* #param array $params Parameters
* #return string Content
*
*/
function hookLeftColumn($params)
{
$tags = Tag::getMainTags((int)($params['cookie']->id_lang), (int)(Configuration::get('BLOCKTAGS_NBR')));
$max = -1;
$min = -1;
foreach ($tags as $tag)
{
if ($tag['times'] > $max)
$max = $tag['times'];
if ($tag['times'] < $min || $min == -1)
$min = $tag['times'];
}
if ($min == $max)
$coef = $max;
else
{
$coef = (BLOCKTAGS_MAX_LEVEL - 1) / ($max - $min);
}
if (!sizeof($tags))
return false;
foreach ($tags AS &$tag)
$tag['class'] = 'tag_level'.(int)(($tag['times'] - $min) * $coef + 1);
$this->smarty->assign('tags', $tags);
return $this->display(__FILE__, 'blocktags.tpl');
}
function hookRightColumn($params)
{
return $this->hookLeftColumn($params);
}
function hookHeader($params)
{
$this->context->controller->addCSS(($this->_path).'blocktags.css', 'all');
}
public function hookdisplayTop($params)
{
return $this->hookdisplayTopColumn($params);
}
public function renderForm()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Displayed tags'),
'name' => 'BLOCKTAGS_NBR',
'class' => 'fixed-width-xs',
'desc' => $this->l('Set the number of tags you would like to see displayed in this block.')
),
),
'submit' => array(
'title' => $this->l('Save'),
)
),
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitBlockTags';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFieldsValues(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
return $helper->generateForm(array($fields_form));
}
public function getConfigFieldsValues()
{
return array(
'BLOCKTAGS_NBR' => Tools::getValue('BLOCKTAGS_NBR', Configuration::get('BLOCKTAGS_NBR')),
);
}
}
Change this:
public function hookdisplayTop($params)
{
return $this->hookdisplayTopColumn($params);
}
To that:
public function hookdisplayTopColumn($params)
{
return $this->hookLeftColumn($params);
}

description isnt displaying for zf2 form element

I am trying to add a description to my form element. I am expecting to get my description in p tags.
<?php
namespace CsnCms\Form;
use Zend\Form\Form;
class ArticleForm extends Form
{
public function __construct($name = null)
{
parent::__construct('article');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'currency',
'attributes' => array(
'type' => 'text',
'placeholder' =>'Currency',
),
'options' => array(
'label' => ' ',
'description' => 'Currency code: ie. USD',
),
));
}
}
unfortunately I am only getting this as an output
<label><span> </span><input name="currency" type="text" placeholder="Currency" value=""></label>
any advice?
Maybe this will work
$form = $this->form;
$element = $form->get("currency");
echo $this->formInput($element);
echo $element->getOption("description"); // <-------
?>
zf2 form elements don't have native description option u need to add it manually :
$this->add(array(
'name' => 'catMachineName',
'type' => 'Zend\Form\Element\Text',
'options' => array(
'label' => 'Category Machine Name',
'description' => 'Machine name can only contain English Alphabets and Numbers and _ and no space and no number at the beginning'
),
));
and render it in view like with something like this:
echo $form->get('catMachineName')->getOption('description);
Thanks I wrote my own view helper. I also added a class="error" in the error tags.
Thanks for the help guys.
<?php
namespace User\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\Form\View\Helper\FormRow;
use Zend\Form\ElementInterface;
class FormRowWithDescription extends FormRow
{
/**
* Utility form helper that renders a label (if it exists), an element and errors
*
* #param ElementInterface $element
* #throws \Zend\Form\Exception\DomainException
* #return string
*/
public function render(ElementInterface $element)
{ $escapeHtmlHelper = $this->getEscapeHtmlHelper();
$labelHelper = $this->getLabelHelper();
$elementHelper = $this->getElementHelper();
$elementErrorsHelper = $this->getElementErrorsHelper();
$label = $element->getLabel();
$inputErrorClass = $this->getInputErrorClass();
if (isset($label) && '' !== $label) {
// Translate the label
if (null !== ($translator = $this->getTranslator())) {
$label = $translator->translate(
$label, $this->getTranslatorTextDomain()
);
}
}
// Does this element have errors ?
if (count($element->getMessages()) > 0 && !empty($inputErrorClass)) {
$classAttributes = ($element->hasAttribute('class') ? $element->getAttribute('class') . ' ' : '');
$classAttributes = $classAttributes . $inputErrorClass;
$element->setAttribute('class', $classAttributes);
}
if ($this->partial) {
$vars = array(
'element' => $element,
'label' => $label,
'labelAttributes' => $this->labelAttributes,
'labelPosition' => $this->labelPosition,
'renderErrors' => $this->renderErrors,
);
return $this->view->render($this->partial, $vars);
}
if ($this->renderErrors) {
$elementErrorsHelper
->setMessageOpenFormat('<ul%s><li class="error">')
->setMessageSeparatorString('</li><li class="error">');
$elementErrors = $elementErrorsHelper->render($element);
}
$elementString = $elementHelper->render($element);
$description = $element->getOption('description');
$elementString.="<p class='description'>".$description."</p>";
if (isset($label) && '' !== $label) {
$label = $escapeHtmlHelper($label);
$labelAttributes = $element->getLabelAttributes();
if (empty($labelAttributes)) {
$labelAttributes = $this->labelAttributes;
}
// Multicheckbox elements have to be handled differently as the HTML standard does not allow nested
// labels. The semantic way is to group them inside a fieldset
$type = $element->getAttribute('type');
if ($type === 'multi_checkbox' || $type === 'radio') {
$markup = sprintf(
'<fieldset><legend>%s</legend>%s</fieldset>',
$label,
$elementString);
} else {
if ($element->hasAttribute('id')) {
$labelOpen = '';
$labelClose = '';
$label = $labelHelper($element);
} else {
$labelOpen = $labelHelper->openTag($labelAttributes);
$labelClose = $labelHelper->closeTag();
}
if ($label !== '' && !$element->hasAttribute('id')) {
$label = '<span>' . $label . '</span>';
}
// Button element is a special case, because label is always rendered inside it
if ($element instanceof Button) {
$labelOpen = $labelClose = $label = '';
}
switch ($this->labelPosition) {
case self::LABEL_PREPEND:
$markup = $labelOpen . $label . $elementString . $labelClose;
break;
case self::LABEL_APPEND:
default:
$markup = $labelOpen . $elementString . $label . $labelClose;
break;
}
}
if ($this->renderErrors) {
$markup .= $elementErrors;
}
} else {
if ($this->renderErrors) {
$markup = $elementString . $elementErrors;
} else {
$markup = $elementString;
}
}
return $markup;
}
}

Functional test and sfWidgetFormChoice with multiple true

I want to test a user editing a form, and in that form there is a <select multiple="multiple">. How do I select or unselect <option>values from that form widget in the functional test?
Form setup:
'regions_list' => new sfWidgetFormDoctrineChoice(array(
'multiple' => true,
'model' => 'Region'
)),
Functional Test:
$browser->
getRoute('profile')->
//setField('profile[regions_list]', '[9][8]')-> // tried syntaxmany combinations
click('Save Profile', array(
'profile' => array(
// 'regions_list' => ???,
// I've tried many combinations even with setField and none made sense and where testable so far
)
))->
with('form')->begin()->
hasErrors(0)->
hasGlobalError(0)->
end()
;
I've never put the with('form') around the click() and this is working on my tests:
$browser->
getRoute('profile')->
click('Save Profile', array(
'profile' => array('regions_list' => array(8,9)
// with: <option value="8">something</option><option value="9">else</option>
// ... and other fields
)
))->
end()->
with('form')->begin()->
debug() -> // added this line so you can see what is happening
hasErrors(0)->
hasGlobalError(0)->
end()
;
Well, after digging in the click() process, I can't get the result I expect.
The solutions follows the problem:
in a <select multiple> tag, I expect that if I don't post any values, it's going to repost it as is, and if I do specify values, it will post only those and not try to control on/off by values.
The way it's reacting now is that the initial values and the chosen values are merged together and the initial values keys matching the chosen values keys are replaced which doesn't make sense to me because those keys or their order are irrelevant. I only care about the option values chosen.
The answer to my question is: You can't do what you expect with the current implementation.
The solution:
Override (or submit a patch if you have time) the doClickElement function in sfBrowserBase class which could look like this: ( look for the 3 comments // fix for select multiple and the last 2 methods to add )
public function doClickElement(DOMElement $item, $arguments = array(), $options = array())
{
$method = strtolower(isset($options['method']) ? $options['method'] : 'get');
if ('a' == $item->nodeName)
{
if (in_array($method, array('post', 'put', 'delete')))
{
if (isset($options['_with_csrf']) && $options['_with_csrf'])
{
$arguments['_with_csrf'] = true;
}
return array($item->getAttribute('href'), $method, $arguments);
}
else
{
return array($item->getAttribute('href'), 'get', $arguments);
}
}
else if ('button' == $item->nodeName || ('input' == $item->nodeName && in_array($item->getAttribute('type'), array('submit', 'button', 'image'))))
{
// add the item's value to the arguments
$this->parseArgumentAsArray($item->getAttribute('name'), $item->getAttribute('value'), $arguments);
// use the ancestor form element
do
{
if (null === $item = $item->parentNode)
{
throw new Exception('The clicked form element does not have a form ancestor.');
}
}
while ('form' != $item->nodeName);
}
// form attributes
$url = $item->getAttribute('action');
if (!$url || '#' == $url)
{
$url = $this->stack[$this->stackPosition]['uri'];
}
$method = strtolower(isset($options['method']) ? $options['method'] : ($item->getAttribute('method') ? $item->getAttribute('method') : 'get'));
// merge form default values and arguments
$defaults = array();
$arguments = sfToolkit::arrayDeepMerge($this->fields, $arguments);
// fix for select multiple
$select_multiple_to_check = array();
$xpath = $this->getResponseDomXpath();
foreach ($xpath->query('descendant::input | descendant::textarea | descendant::select', $item) as $element)
{
if ($element->hasAttribute('disabled'))
{
continue;
}
$elementName = $element->getAttribute('name');
$nodeName = $element->nodeName;
$value = null;
if ($nodeName == 'input' && ($element->getAttribute('type') == 'checkbox' || $element->getAttribute('type') == 'radio'))
{
// fix for select multiple
if (substr($elementName, -2) == '[]')
{
$select_multiple_to_check[$elementName] = true;
}
if ($element->getAttribute('checked'))
{
$value = $element->hasAttribute('value') ? $element->getAttribute('value') : '1';
}
}
else if ($nodeName == 'input' && $element->getAttribute('type') == 'file')
{
$filename = array_key_exists($elementName, $arguments) ? $arguments[$elementName] : sfToolkit::getArrayValueForPath($arguments, $elementName, '');
if (is_readable($filename))
{
$fileError = UPLOAD_ERR_OK;
$fileSize = filesize($filename);
}
else
{
$fileError = UPLOAD_ERR_NO_FILE;
$fileSize = 0;
}
unset($arguments[$elementName]);
$this->parseArgumentAsArray($elementName, array('name' => basename($filename), 'type' => '', 'tmp_name' => $filename, 'error' => $fileError, 'size' => $fileSize), $this->files);
}
else if ('input' == $nodeName && !in_array($element->getAttribute('type'), array('submit', 'button', 'image')))
{
$value = $element->getAttribute('value');
}
else if ($nodeName == 'textarea')
{
$value = '';
foreach ($element->childNodes as $el)
{
$value .= $this->getResponseDom()->saveXML($el);
}
}
else if ($nodeName == 'select')
{
if ($multiple = $element->hasAttribute('multiple'))
{
// fix for select multiple
$select_multiple_to_check[$elementName] = true;
$elementName = str_replace('[]', '', $elementName);
$value = array();
}
else
{
$value = null;
}
$found = false;
foreach ($xpath->query('descendant::option', $element) as $option)
{
if ($option->getAttribute('selected'))
{
$found = true;
if ($multiple)
{
$value[] = $option->getAttribute('value');
}
else
{
$value = $option->getAttribute('value');
}
}
}
$option = $xpath->query('descendant::option', $element)->item(0);
if (!$found && !$multiple && $option instanceof DOMElement)
{
$value = $option->getAttribute('value');
}
}
if (null !== $value)
{
$this->parseArgumentAsArray($elementName, $value, $defaults);
}
}
// fix for select multiple
foreach($select_multiple_to_check as $elementName => $uselessbool)
{
$path = array_filter(preg_split('/(\[ | \[\] | \])/x', $elementName), create_function('$s', 'return $s !== "";'));
if ($this->findInArrayByArrayPath($arguments, $path) !== false)
{
$this->unsetInArrayByArrayPath($defaults, $path);
}
}
$arguments = sfToolkit::arrayDeepMerge($defaults, $arguments);
if (in_array($method, array('post', 'put', 'delete')))
{
return array($url, $method, $arguments);
}
else
{
$queryString = http_build_query($arguments, null, '&');
$sep = false === strpos($url, '?') ? '?' : '&';
return array($url.($queryString ? $sep.$queryString : ''), 'get', array());
}
}
// fix for select multiple
// taken from http://stackoverflow.com/questions/3145068/set-multi-dimensional-array-by-key-path-from-array-values/3145199#3145199
public function findInArrayByArrayPath(&$array, &$path, $_i=0) {
// sanity check
if ( !(is_array($array) && is_array($path)) ) return false;
$c = count($path); if ($_i >= $c) return false;
if ($_i==0) {$path = array_values($path);} // to make sure we don't get skipped numeric keys which does happens in the preg_split above
$k = $path[$_i];
if (array_key_exists($k, $array))
return ($_i == $c-1) ? $array[$k] : $this->findInArrayByArrayPath($array[$k], $path, $_i+1);
else
return false;
}
// fix for select multiple
public function unsetInArrayByArrayPath(&$array, &$path, $_i=0) {
// sanity check
if ( !(is_array($array) && is_array($path)) ) return false;
$c = count($path); if ($_i >= $c) return false;
if ($_i==0) {$path = array_values($path);} // to make sure we don't get skipped numeric keys which does happens in the preg_split above
$k = $path[$_i];
if (array_key_exists($k, $array))
if ($_i == $c-1) {
unset($array[$k]);
return true;
} else {
return $this->unsetInArrayByArrayPath($array[$k], $path, $_i+1);
}
else
return false;
}
And Now:
'profile' => array('regions_list' => array(8,9)) works for me.

Resources