I am using JS Helper submit in my cakephp 2.x version.
My code is fine as function is called.
<?php echo $this->Js->submit("Apply", array(
'div' => false,
'class' => 'general_button',
'style' => array('float:none;', 'margin: 10px;'),
'url' => array('controller' => 'poets', 'action' => 'index', 'field' => $search_term, 'value' => $search_value),
'update' => '#listID',
'confirm' => 'Are you sure you want to apply action to selected records ??',
'before' => "return isAnySelect(this.form);",
'success' => 'myShowMessage();')); ?>
Though function isAnySelect(this.form) is called but my function this.form returns undefined wats the issue with this code .. Please explain.
My function
function isAnySelect(frmObject) {
console.log(frmObject);
return false;
varAllId = "";
for (i = 1; i < frmObject.chkRecordId.length; i++) {
alert('Hiii');
alert(varAllId + "xs");
if (frmObject.chkRecordId[i].checked == true) {
if (varAllId == "") {
varAllId = frmObject.chkRecordId[i].value;
} else {
varAllId += "," + frmObject.chkRecordId[i].value;
}
}
}
if (varAllId == "") {
alert("Please select atleast one record !!");
return false;
} else {
document.getElementById('idList').value = varAllId;
return true;
}
}
Though function is called but it output undefined on console.
Related
I'm having some issues with some Loop for Custom Catalog Listing.
The goal: have Simple Products and some Variant Products (depend on the attribute) listed on the catalog page;
I created a custom product loop using wc_get_products with the type array('simple', 'variation') but attribute filters like size or color don't work with this listing.
This is the code:
$category = get_queried_object();
$currentCat = "";
if ( $category->slug != NULL ){
$currentCat = array($category->slug);
}
$paged = (get_query_var('paged')) ? absint(get_query_var('paged')) : 1;
$ordering = WC()->query->get_catalog_ordering_args();
$ordering['orderby'] = array_shift(explode(' ', $ordering['orderby']));
$ordering['orderby'] = stristr($ordering['orderby'], 'price') ? 'meta_value_num' : $ordering['orderby'];
$products_per_page = apply_filters('loop_shop_per_page', wc_get_default_products_per_row() * wc_get_default_product_rows_per_page());
$list_products = wc_get_products(array(
'meta_key' => '_price',
'status' => 'publish',
'category' => $currentCat,
'type' => array('simple', 'variation'),
'limit' => $products_per_page,
'page' => $paged,
'paginate' => true,
'return' => 'ids',
'orderby' => $ordering['orderby'],
'order' => $ordering['order'],
));
$totalProducts = (array) $list_products->products;
wc_set_loop_prop('current_page', $paged);
wc_set_loop_prop('is_paginated', wc_string_to_bool(true));
wc_set_loop_prop('page_template', get_page_template_slug());
wc_set_loop_prop('per_page', $products_per_page);
wc_set_loop_prop('total', $list_products->total);
wc_set_loop_prop('total_pages', $list_products->max_num_pages);
if($totalProducts) {
do_action('woocommerce_before_shop_loop');
woocommerce_product_loop_start();
foreach($totalProducts as $productID) {
$post_object = get_post($productID);
setup_postdata($GLOBALS['post'] =& $post_object);
wc_get_template_part('content', 'product');
}
wp_reset_postdata();
woocommerce_product_loop_end();
do_action('woocommerce_after_shop_loop');
} else {
do_action('woocommerce_no_products_found');
}
Anyone can give me an hand, so that filters start working??
Just got the way to put it to work:
1st I have a loop to get all the product ID's with a condition in the variations to confirm if a custom field (checkbox) is checked. This is mainly to get the total number of products to set up pagination.
The Goal is to include only the Variations Checked on the Catalog Page.
After, I'm doing a second loop, to get all products retrieved from the previous loop.
Here is the working solution:
if(!function_exists('wc_get_products')) {
return;
}
function get_issues($term) {
$hlterms = get_terms($term);
foreach($hlterms as $term){
// var_dump($term->taxonomy);
return true;
}
}
// Get all Attribute Filters
$outputFilters = "";
foreach($_GET as $key => $querystring){
if (strpos($key, 'filter') !== false) {
$outputFilters = array();
$newkey = str_replace("filter", "pa", $key);
if (get_issues($newkey) === true){
$outputFilters[$newkey] = $querystring;
}
}
}
// Check if in some Category
$category = get_queried_object();
$currentCat = "";
if ( $_GET['product_cat'] != NULL ){
$currentCat = $_GET['product_cat'];
} else if ($category->slug != NULL){
$currentCat = array($category->slug);
}
// 1st Loop to get total IDs
$paged = (get_query_var('paged')) ? absint(get_query_var('paged')) : 1;
$products_per_page = apply_filters('loop_shop_per_page', wc_get_default_products_per_row() * wc_get_default_product_rows_per_page());
$ordering['orderby'] = 'id';
$args = array(
'meta_key' => '_price',
'status' => 'publish',
'category' => $currentCat,
'type' => array('simple', 'variation'),
'limit' => 1000,
'paginate' => true,
'return' => 'ids',
);
if ($outputFilters != ""){
$args = array_merge($args, $outputFilters);
}
$list_products = wc_get_products($args);
$totalProducts = (array) $list_products->products;
$productsIDS = array();
foreach($totalProducts as $productID) {
$product_s = wc_get_product( $productID );
if ($product_s->product_type == 'simple') {
array_push($productsIDS, $productID);
} else {
if ($product_s->product_type == 'variation') {
$showCatalog = get_post_meta( $productID, '_showoncatalog', true );
if ($showCatalog == "yes"){
array_push($productsIDS, $productID);
}
}
}
}
// Final loop
$args = array(
'meta_key' => '_price',
'status' => 'publish',
'category' => $currentCat,
'type' => array('simple', 'variation'),
'limit' => $products_per_page,
'page' => $paged,
'paginate' => true,
'return' => 'ids',
'orderby' => $ordering['orderby'],
'order' => $ordering['order'],
'include' => $productsIDS,
);
if ($outputFilters != ""){
$args = array_merge($args, $outputFilters);
}
$list_products = wc_get_products($args);
$totalProducts = (array) $list_products->products;
wc_set_loop_prop('current_page', $paged);
wc_set_loop_prop('is_paginated', wc_string_to_bool(true));
wc_set_loop_prop('page_template', get_page_template_slug());
wc_set_loop_prop('per_page', $products_per_page);
wc_set_loop_prop('total', $list_products->total);
wc_set_loop_prop('total_pages', $list_products->max_num_pages);
if($totalProducts) {
do_action('woocommerce_before_shop_loop');
woocommerce_product_loop_start();
foreach($totalProducts as $productID) {
$post_object = get_post($productID);
setup_postdata($GLOBALS['post'] =& $post_object);
wc_get_template_part('content', 'product');
}
wp_reset_postdata();
woocommerce_product_loop_end();
do_action('woocommerce_after_shop_loop');
} else {
do_action('woocommerce_no_products_found');
}
/**
* Hook: woocommerce_after_shop_loop.
*
* #hooked woocommerce_pagination - 10
*/
#do_action( 'woocommerce_after_shop_loop' );
}
I made the code below in order to validate a transaction in which the balance and history would be saved in the database or none of them. However, when I run the code and check the database I see that the balance is still being inserted into the bank instead of being canceled. What could be the mistake?
Below is the method code of my balance model responsible for the operation
public function deposit(float $value) : Array {
DB::beginTransaction();
$totalBefore = null;
// $totalBefore = $this->amount ? $this->amount : 0;
$this->amount += number_format($value, 2, ".", '');
$deposit = $this->save();
$historic = auth()->user()->historics()->create([
'type' => 'I',
'amount' => $value,
'total_before' => $totalBefore,
'total_after' => $this->amount,
'date' => date('Ymd'),
]);
if ($deposit && $historic) {
DB::commit();
return [
'success' => true,
'message' => 'Sucesso ao recarregar!'
];
}
else {
DB::rollBack();
return [
'success' => false,
'message' => 'Falha ao recarregar!'
];
}
}
When you use save() it is not getting rolled back by db::rollBack().
I'm trying to create a module that will display some last entries from database. I'd like to send last entry object to template file (guestbook-last-entries.tpl.php), that looks like that
<p><?php render($title); ?></p>
<?php echo $message; ?>
I have a function that implements hook_theme
function guestbook_theme() {
return array(
'guestbook_last_entries' => array(
'variables' => array(
'entries' => NULL,
),
'template' => 'guestbook-last-entries'
),
);
}
one that do preprocess
function template_preprocess_guestbook_last_entries(&$variables) {
$variables = array_merge((array) $variables['entries'], $variables);
}
and functions that implements hook_block_view
function guestbook_block_view($delta = '') {
switch ($delta) {
case 'guestbook_last_entries':
$block['subject'] = t('Last entries');
$block['content'] = array();
$entries = guestbook_get_last_entries(variable_get('guestbook_m', 3));
foreach ($entries as $entry) {
$block['content'] += array(
'#theme' => 'guestbook_last_entries',
'#entries' => $entry,
);
}
break;
}
return $block;
}
function that gets data from database
function guestbook_get_last_entries($limit = 3) {
$result = db_select('guestbook', 'g')
->fields('g')
->orderBy('posted', 'DESC')
->range(0, $limit)
->execute();
return $result->fetchAllAssoc('gid');
}
But in this case I get only one entry displayed. Can anyone tell me how to resolve this, how should I build that $block['content']?
Thank you
This here wont work:
$block['content'] += array(
'#theme' => 'guestbook_last_entries',
'#entries' => $entry,
);
Maybe you want this if you need an array as the result:
// note that I replaced += with a simple = and added two brackets that will create a new element in that array $block['content']
$block['content'][] = array(
'#theme' => 'guestbook_last_entries',
'#entries' => $entry,
);
This might be easy, but I have tried a few ideas but no solution at all, I'm no expert with cakePhp but I'm trying to modify a existing project with limited time.
The problem is that I have a entity called 'centro' but I'm using its model on a different controller, 'rw', but I can't get it to pass that data to the view at all; it seems it's because the variable gets erased when I use a redirect to go back to the 'index'.
I need that data to generate a google map, the method $this->set(.....) is not working.
Here's the code of the 'rw' controller.
<?php
class RwController extends AppController {
var $name = 'Rw';
// var $paginate = array(
// 'Tip' => array(
// 'limit' => 1,
// 'order' => array(
// 'tip.created' => 'desc'
// ),
// ),
// 'Evento' => array(
// 'limit' => 1,
// 'order' => array(
// 'evento.fecha' => 'desc'
// ),
// )
// );
function map() {
$this->helpers[]='GoogleMapV3';
}
function pageForPagination($model) {
$page = 1;
// $chars = preg_split('/model:/', $this->params['url']['url'], -1, PREG_SPLIT_OFFSET_CAPTURE);
// #print_r($chars);
// if(sizeof($chars) > 1 && sizeof($chars) < 3) {
// #echo "Belongs to ".$model.": \n";
// #echo var_dump($chars);
// }
// $params = Dispatcher::parseParams(Dispatcher::uri());
// echo "<p>".var_dump($params)."</p><br />";
#echo $this->params['named']['model'].$model;
#echo $this->params['named']['page'];
$sameModel = isset($this->params['named']['model']) && $this->params['named']['model'] == $model;
$pageInUrl = isset($this->params['named']['page']);
if ($sameModel && $pageInUrl) {
$page = $this->params['named']['page'];
} else {
#echo var_dump($this->passedArgs);
}
$this->passedArgs['page'] = $page;
return $page;
}
function index() {
$this->loadModel('User');
$this->loadModel('Evento');
$this->loadModel('Tip');
$dataEvento = $this->Evento->find('all');
$dataTip = $this->Tip->find('all');
$page = $this->pageForPagination('Evento');
$this->paginate['Evento'] = array(
'contain' => false,
'order' => array('Evento.fecha' => 'desc'),
'limit' => 1,
'page' => $page
);
$dataEvento = $this->paginate('Evento');
$page = $this->pageForPagination('Tip');
$this->paginate['Tip'] = array(
'contain' => false,
'order' => array('Tip.created' => 'desc'),
'limit' => 1,
'page' => $page
);
$dataTip = $this->paginate('Tip');
$this->set('users', $this->User->find('all'));
$this->set('eventos', $dataEvento);
$this->set('tips', $dataTip);
$this->set('rw');
if(isset($this->params['named']['model'])) {
if (strcmp($this->params['named']['model'], 'Evento') == 0) {
if($this->RequestHandler->isAjax()) {
$this->render('/elements/ajax_rw_evento_paginate');
return;
}
} elseif (strcmp($this->params['named']['model'], 'Tip') == 0) {
if($this->RequestHandler->isAjax()) {
$this->render('/elements/ajax_rw_tip_paginate');
return;
}
}
}
}
function about($id = null) {
$this->Rw->recursive = 0;
$this->set('rw', $this->paginate());
}
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array('*'));
}
function getCentros($id = null ){
$this->loadModel('Centro');
$this->log('getcentros','debug');
$this->log('el id'.$id,'debug');
if( sizeof($id) > 1){
$this->set('centros', $this->Centro->query("SELECT centros.id, name, latitud ,longitud
FROM `centros`,`centrosmateriales`
WHERE centros.id = centro_id
AND material_id ='".$id[0]."'
OR material_id='".$id[1]."'"));
$this->log('size id > 1 ','debug');
}elseif( sizeof($id) >0) {
if($id == 0){
$this->set('centros', $this->Centro->find('all'));
}else{
$this->set('centros', $this->Centro->query("SELECT centros.id, name, latitud ,longitud
FROM `centros`,`centrosmateriales`
WHERE centros.id = centro_id
AND material_id ='".$id[0]."'"));
}
}
$this->Session->write('saludos', 'Saludando');
$this->redirect(array('action' => 'index'));
}
}
?>
I have been thinking about ajax but I'm not sure.
Anyways, thanks in advance.
Using redirect() sends an actual HTTP redirect to the browser. This causes the browser to send another request to the server, to the URL it has been redirected to.
The data that you pass to set() is only available within that single CakePHP request cycle. All PHP data is wiped from memory afterwards. The only way to pass data to the next request is in the URL or in the session.
In your case you should rethink your design and set() all data you need in the index() action. You could possibly move the logic from getCentros() into your Centro model. Then, in your index() function, you could just do
$this->set(
'centro',
$this->Centro->getCentros();
);
I need to create content that only outputs what I entered, no layout, no comments, blocks, etc.
If I could implement a custom content type that used blank templates that might work, but I've been unable to make it work so far as overriding the themes seems to replace everything site-wide. So, skipping that, is there a simple way I'm not aware of, to just output what I type in the content's body, with no layout/blocks/comments,etc.
Is it possible via a custom module to add a custom field at the bottom, and then during the process_page() hook, ignore the theming and layout and just output the content?
Please don't suggest "Views" as it's not stable.
Some example use cases:
A page that's a PHP type, and it's simply a script that I don't want layout as an example.
Or if I have some json data to return.
Or if I want to toss up a all-in-one page with it's own theme.
Any suggestions?
I am working on a module that will do this and also integrate with views so you can set a view to be "theme-less" as well. I have it so that it will create a checkbox on a node form that you can specify the node to be theme-less node. Once that is checked, the node will be displayed with no theme (the content only, no title).
It's a little hackish, but it works preliminarily. I will be fleshing this out as I have need for it and I will likely also integrate it with views over time.
timeless.install
<?php
/**
* themeless.install
* defines our schema for flagging nodes as being themeless or not.
*/
function themeless_schema() {
$schema['themeless_node'] = array(
'description' => 'Keeps track of which nodes are themeless.',
'fields' => array(
'nid' => array(
'description' => 'The node id of a themeless node',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
),
'primary_key' => array('nid'),
);
return $schema;
}
function themeless_enable() {
if (db_table_exists('themeless_node') == FALSE) {
drupal_install_schema('themeless');
}
}
function themeless_uninstall() {
drupal_uninstall_schema('themeless');
}
timeless.module
function themeless_process(&$variables, $hook) {
if ($hook == 'page') {
if (isset($variables['page']['content']['system_main']['nodes']) && is_array($variables['page']['content']['system_main']['nodes'])) {
$node = $variables['page']['content']['system_main']['nodes'];
$nodes = array_keys($node);
$result = db_query("SELECT t.nid AS themeless, n.promote
FROM {themeless_node} t, {node} n
WHERE t.nid=:nid
AND n.nid=t.nid",
array('nid' => $nodes[0]));
$tdata = $result->fetchObject();
if (isset($tdata->themeless) && $tdata->themeless > 0 && $tdata->promote != 1) {
if ($node[$nodes[0]]['body']['#object']->body['und'][0]['format'] == 'php_code') {
print $node[$nodes[0]]['body'][0]['#markup'];
} else {
print $node[$nodes[0]]['body']['#object']->body['und'][0]['value'];
}
exit();
}
}
}
}
function themeless_form_alter(&$form, &$form_state, $form_id) {
$parts = explode('_',$form_id);
$form_type = $parts[count($parts)-1].'_'.$parts[count($parts)-2];
$themeless = '';
if ($form_type == 'form_node') {
if (isset($form_state['node']->nid) && $form_state['node']->nid) {
$themeless = db_query("SELECT COUNT(*) AS themeless
FROM {themeless_node}
WHERE nid=:nid",
array('nid' => $form_state['node']->nid))->fetchField();
}
$checked = ($themeless == 1) ? 'checked' : '';
$form['themeless'] = array(
'#type' => 'fieldset',
'#title' => t('Themeless Node'),
'#weight' => 5,
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['themeless']['themeless_node'] = array(
'#type' => 'checkbox',
'#title' => 'Themeless Node',
'#description' => 'This theme will be displayed without any wrapper themes.',
'#weight' => 100,
'#default_value' => $themeless,
);
}
}
function themeless_node_insert($node) {
$result = db_query("INSERT INTO {themeless_node} (nid)
VALUES( :nid )",array('nid' => $node->nid));
}
function themeless_node_update($node) {
if ($node->themeless_node == 1) {
if (db_query("SELECT COUNT(*) AS themeless
FROM {themeless_node}
WHERE nid=:nid",
array('nid' => $node->nid))->fetchField() != 1) {
$result = db_query("INSERT INTO {themeless_node} (nid)
VALUES( :nid )",array('nid' => $node->nid));
}
} else {
$result = db_query("DELETE FROM {themeless_node}
WHERE nid=:nid",array('nid' => $node->nid));
}
}
timeless.info
name = Themeless
description = Gives the option to a node to have a themeless display or displayed without the various theme templates native to Drupal.
core = 7.x
version = 7.x-1.0dev