Duplicate entry '2' for key 'PRIMARY' on Auto Modeller Update Function in Kohana - kohana-3

Am trying to perform an update and nothing seems to work. It has something to do with my callback I suppose as the update works well when the callback is disabled. This is my try block.
try{
$updatestat=NULL;
$updateresult=NULL;
$id = Arr::get($_POST, 'id');
$scode=trim(Arr::get($_POST, 'stationcode'));
$sname=trim(Arr::get($_POST, 'stationname'));
$dsupdate = new Model_Dstations($id);
$dsupdate->scode = $scode;
$dsupdate->sname = $sname;
$validation = new Validation($_POST);
$validation->rule('scode', array($dsupdate, 'check_updatecheck' ), array( ':validation', ':value',':field',$id ));
$validation->rule('sname', array($dsupdate, 'check_updatecheck' ), array( ':validation', ':value',':field',$id ));
$result['sql']=$dsupdate->save($validation);}

Your code looks like a complete mess.
Try this:
$dsupdate = new Model_Dstations($id);
$validation = new Validation($_POST);
$validation->rule('scode', array($dsupdate, 'check_updatecheck' ), array( ':validation', ':value',':field',$id ));
$validation->rule('sname', array($dsupdate, 'check_updatecheck' ), array( ':validation', ':value',':field',$id ));
if ($validation->check()) {
$dsupdate->scode = $scode;
$dsupdate->sname = $sname;
$dsupdate->save();
}

Related

WordPress default gallery pagination when call is in page, not post?

It seems I have found the way to make WordPress default gallery pagination to work and to have control over URL forming: https://wordpress.stackexchange.com/questions/401034/pagination-with-wordpress-default-gallery But when gallery call is in post.
When gallery call is in page, it works only if URL is like this: domain.com/pagename/page/2/, domain.com/pagename/page/3/ etc. Trying to have a different URL ends up in stopping it to work.
The part of code handling pagination in functions.php:
// Pagination Setup
$current = (get_query_var('paged')) ? get_query_var( 'paged' ) : 1;
$per_page = 3;
$offset = ($current-1) * $per_page;
$big = 999999999;
$total = sizeof($attachments);
$total_pages = round($total/$per_page);
if( $total_pages < ( $total/$per_page ) ){
$total_pages = $total_pages+1;
}
// Pagination output
$output .= paginate_links( array(
'base' => str_replace($big,'%#%',esc_url(get_pagenum_link($big))),
'format' => '?paged=%#%',
'current' => $current,
'total' => $total_pages,
'prev_text' => __('«'),
'next_text' => __('»')
) );
As long as I keep URL like this domain.com/pagename/page/2/ , other ways for 'base' also work:
'base' => get_permalink( $post->post_parent ) . '%_%',
'format' => 'page/%#%/',
And like this:
'base' => get_pagenum_link( 1 ) . '%_%',
'format' => 'page/%#%/',
But when I try some other URL scheme:
'base' => get_permalink( $post->post_parent ) . '%_%',
'format' => 'paging-%#%',
pagination stops working.
The filter with rewrite tag and rule:
add_filter('init', 'post_gallery_add_rewrite_tag_rule_2022');
function post_gallery_add_rewrite_tag_rule_2022() {
add_rewrite_tag('%current%','(.+)');
add_rewrite_rule('(.+)/paging-/?([0-9]{1,})/?$', 'index.php?name=$matches[1]&paged=$matches[2]', 'top');
}
It seems like add_rewrite_rule is not functioning when gallery call is in page? Or what? Any ideas?

Wordpress: Pass $wpdb->insert_id from 1 function to another?

I'm trying to do something simple. I think my code looks sound, but for some reason, the $wpdb->insert_id; keeps being empty? Am I doing something wrong here? Am I doing the passing of the variable correctly? I even tried storing $wpdb->insert_id; in a $_SESSION but it was still empty.
function insert_stuff() {
global $wpdb;
$wpdb->insert('mytable',
array(
'column1' => $_REQUEST['formitem1'],
'column2' => $_REQUEST['formitem2'],
)
);
global $lastid;
$lastid = $wpdb->insert_id;
}
add_action('add_to_cart', 'insert_stuff');
function update_stuff() {
global $wpdb;
global $lastid;
$wpdb->update('mytable', array('column3' => 'newvalue'), array('id' => $lastid), array('%s'), array('%d'));
}
add_action('thank_you_page', 'update_stuff');
Looks like you are missing an array with the $wpdb->insert..
$wpdb->insert(
'table',
array(
'column1' => $var1,
'column2' => $var2,
),
array(
'%d',
'%s',
)
);
Note: %d = numbers.. %s = string..
Best of luck.

How to implement a pagination for a search module in Zend Framework 2?

I have a module Search in my ZF2 application. The user fills in a search form out and gets a list of courses.
Now I'm adding the pagination to the module. The paginator is basically working: I can retrieve data over it and the pagination is displayed correctly (pagelinks 1-7 for 70 found courses with the dafault setting 10 items per page).
But it's still not usable. When I click on a pagelink, the form POST data is lost. I know -- it cannot work the way, how I implemented it (see the code below). But I have no idea, how to do it correctly, in order to eep checking the form data and nonetheless be able to use pagination.
That is my code:
Table class Search\Model\CourseTable
class CourseTable {
...
// without pagination
// public function findAllByCriteria(CourseSearchInput $input) {
// with pagination
public function findAllByCriteria(CourseSearchInput $input, $pageNumber) {
...
$select = new Select();
$where = new Where();
$having = new Having();
...
// without pagination
// $resultSet = $this->tableGateway->selectWith($select);
// return $resultSet;
// with pagination
$adapter = new \MyNamespqce\Paginator\Adapter\DbSelect($select, $this->tableGateway->getAdapter());
$paginator = new \Zend\Paginator\Paginator($adapter);
$paginator->setCurrentPageNumber($pageNumber);
return $paginator;
}
...
}
Search\Controller\SearchController
class SearchController extends AbstractActionController {
public function searchCoursesAction() {
$form = $this->getServiceLocator()->get('Search\Form\CourseSearchForm');
$request = $this->getRequest();
if ($request->isPost()) {
$courseSearchInput = new CourseSearchInput();
$form->setInputFilter($courseSearchInput->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$courseSearchInput->exchangeArray($form->getData());
// without pagination
// $courses = $this->getCourseTable()->findAllByCriteria($courseSearchInput);
// with pagination
$page = $this->params()->fromRoute('page');
$paginator = $this->getCourseTable()->findAllByCriteria($courseSearchInput, $page);
} else {
$paginator = null;
}
} else {
$paginator = null;
}
return new ViewModel(array(
'form' => $form,
// without pagination
// 'courses' => $courses,
// with pagination
'paginator' => $paginator,
'cities' => ...
));
}
...
}
How to get it working?
I also have the same problem, and I have solved it. But this is not good way. May be the idea will help you.
I solved it as follow: (Search pagination for Zend tutorial album module)
I build two action in controller named "search" and "index".
Whenever the search form submitted, it always post the value to search action. Search action build the url with search parameters, and redirect to index to disply search result.
And when the pagination links clicked, then posted values are passed through url. So whenever index action ask for search parameters, it always get the values in same format.
I defined route as follows:
'album' => array(
'type' => 'segment',
'options' => array(
'route' => '/album[/:action][/:id][/page/:page][/order_by/:order_by][/:order][/search_by/:search_by]',
'constraints' => array(
'action' => '(?!\bpage\b)(?!\border_by\b)(?!\bsearch_by\b)[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
'page' => '[0-9]+',
'order_by' => '[a-zA-Z][a-zA-Z0-9_-]*',
'order' => 'ASC|DESC',
),
'defaults' => array(
'controller' => 'Album\Controller\Album',
'action' => 'index',
),
),
),
There is a parameter named "search_by", which will keep all search parameters as a json string. This is the point, which is not good I know, but have not find any other way yet.
"Search" action build this string as -
public function searchAction()
{
$request = $this->getRequest();
$url = 'index';
if ($request->isPost()) {
$formdata = (array) $request->getPost();
$search_data = array();
foreach ($formdata as $key => $value) {
if ($key != 'submit') {
if (!empty($value)) {
$search_data[$key] = $value;
}
}
}
if (!empty($search_data)) {
$search_by = json_encode($search_data);
$url .= '/search_by/' . $search_by;
}
}
$this->redirect()->toUrl($url);
}
And next index action decode the string, do necessary action, and also send the json string to view.
public function indexAction() {
$searchform = new AlbumSearchForm();
$searchform->get('submit')->setValue('Search');
$select = new Select();
$order_by = $this->params()->fromRoute('order_by') ?
$this->params()->fromRoute('order_by') : 'id';
$order = $this->params()->fromRoute('order') ?
$this->params()->fromRoute('order') : Select::ORDER_ASCENDING;
$page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
$select->order($order_by . ' ' . $order);
$search_by = $this->params()->fromRoute('search_by') ?
$this->params()->fromRoute('search_by') : '';
$where = new \Zend\Db\Sql\Where();
$formdata = array();
if (!empty($search_by)) {
$formdata = (array) json_decode($search_by);
if (!empty($formdata['artist'])) {
$where->addPredicate(
new \Zend\Db\Sql\Predicate\Like('artist', '%' . $formdata['artist'] . '%')
);
}
if (!empty($formdata['title'])) {
$where->addPredicate(
new \Zend\Db\Sql\Predicate\Like('title', '%' . $formdata['title'] . '%')
);
}
}
if (!empty($where)) {
$select->where($where);
}
$album = $this->getAlbumTable()->fetchAll($select);
$totalRecord = $album->count();
$itemsPerPage = 2;
$album->current();
$paginator = new Paginator(new paginatorIterator($album));
$paginator->setCurrentPageNumber($page)
->setItemCountPerPage($itemsPerPage)
->setPageRange(7);
$searchform->setData($formdata);
return new ViewModel(array(
'search_by' => $search_by,
'order_by' => $order_by,
'order' => $order,
'page' => $page,
'paginator' => $paginator,
'pageAction' => 'album',
'form' => $searchform,
'totalRecord' => $totalRecord
));
}
All the sorting and paging url contain that string.
If you know all the searching paarameters before, then you can define that at route, and pass like the same way without json string. As I have to build a common search, I have build a single string.
Source code for "Album search" is available in git hub at https://github.com/tahmina8765/zf2_search_with_pagination_example.
Live Demo: http://zf2pagination.lifencolor.com/public/album
#Sam & #automatix in the question comments are both right. My suggestion (though I'm looking for a simpler alternative) is to construct a segment route, which covers all of the options that you're likely to need and start with a standard form POST request.
Then, after the request is validated, pass the form data to the paginationControl helper as follows:
$resultsView = new ViewModel(array(
'paginator' => $paginator,
'routeParams' => array_filter($form->getData())
));
Then, in your view template, set the route parameters in the paginationControl view helper:
<?php echo $this->paginationControl($paginator, 'Sliding', 'paginator/default',
array('routeParams' => $routeParams)
) ?>
I've used array_filter here because it's a really simple way of removing any element from the form data that's null, empty or so on. That way you don't pass in extra data that you don't need.

How to link custom results in Drupal

My first time here an a newbee in Drupal and programming .
So I have a problem I need to some help with.
function query_results($searchstring, $datefrom) {
$tidresult = db_query("SELECT tid FROM {term_data} WHERE LOWER(name) = '%s'", strtolower($searchstring));
$resultarray = array();
while ($obj = db_fetch_object($tidresult)) {
$tid = $obj->tid;
$noderesults = db_query("SELECT n.nid, n.title FROM {node} n
INNER JOIN {term_node} tn ON tn.nid = n.nid
WHERE tn.tid='%s'", $tid);
while ($nodeobj = db_fetch_object($noderesults)) {
$resultarray[$nodeobj->nid] = $nodeobj->title;
}
}
$header = array(
array('data' => 'Nr.'),
array('data' => 'Name'),
);
$rows = array();
$i = 0;
foreach($resultarray as $nid => $title) {
$i++;
$rows[] = array('data' =>
array(
$i,
$title,
),
);
}
$output = theme('table', $header, $rows);
print theme("page", $output);
}
It's driving me crazy , i dint put all of the search code but it takes taxonomy tags from the database ( you type in textbox that has autocomplete, '$searchstring' ) and date ( you choose a time line like one day , yesterday ect. , '$datefrom').
For example reasons lets say it looks like this example when you click search.
I can't post my one pictures but I just gives me the titles ( like above but the are not listed) that I cannot click to lead me to the content.
But I wont it to look like result that is like content ( story ) so you have a clickable Title and some description , like this click to see example
where it says lorem ipsum and that text belowe.
If it is hard to make like in the picture can someone show me just how to make( like in the first picture) the results that are non clickable titles into clickable links that lead me to the content.
To get linked titles you need to use the l() function.
looking at the code you provided, I am not entirely sure how you are getting any results since you save the titles in $resultArray but use $rows when rendering the table.
Unless, $rows is specified somewhere else, $resultarray[$nodeobj->nid] = $nodeobj->title; should become $rows[$nodeobj->nid] = $nodeobj->title;
To make it match your table header, you need to add another 'cell' for the number column
$rows[$nodeobj->nid] = array(
$count++,
l($nodeobj->title, 'node/'.$nodeobj->nid)
);
To provide the excerpt too, you need to join the node_revisions table and get either the body or teaser column, then add it to your rows like this:
$rows[$nodeobj->nid] = array(
$count++,
'<h2>'. l($nodeobj->title, 'node/'.$nodeobj->nid) .'</h2>'. $nodeobj->teaser
);
assuming you get the teaser.
EDIT
the previous answer still holds. You can also simplify the code a bit by processing $rows straight in the $noderesults loop.
function query_results($searchstring, $datefrom) {
$tidresult = db_query("SELECT tid FROM {term_data} WHERE LOWER(name) = '%s'", strtolower($searchstring));
$rows = array();
$count = 0;
while ($obj = db_fetch_object($tidresult)) {
$tid = $obj->tid;
$noderesults = db_query("SELECT n.nid, n.title FROM {node} n "
."INNER JOIN {term_node} tn ON tn.nid = n.nid "
."WHERE tn.tid='%s'", $tid);
while ($nodeobj = db_fetch_object($noderesults)) {
$rows[] = array(
++$count,
l($nodeobj->title, 'node/'. $nodeobj->title)
);
}
}
$header = array(
array('data' => 'Nr.'),
array('data' => 'Name'),
);
$output = theme('table', $header, $rows);
print theme("page", $output);
}
-OR-
move it all in one query (note: I did not get a chance to test this, but I usually get it right the first time):
function query_results($searchstring, $datefrom) {
$rows = array();
$count = 0;
$results = db_query("SELECT n.nid, n.title
FROM {node} n
INNER JOIN {term_node} tn ON tn.nid = n.nid
WHERE tn.tid IN (SELECT tid FROM {term_data} WHERE LOWER(name) = '%s')", strtolower($searchstring));
while ($nodeobj = db_fetch_object($results)) {
$rows[] = array(
++$count,
l($nodeobj->title, 'node/'. $nodeobj->title)
);
}
$header = array(
array('data' => 'Nr.'),
array('data' => 'Name'),
);
$output = theme('table', $header, $rows);
print theme("page", $output);
}

drupal form api checkboxes

I am using drupal form api and using checkboxes. I am getting problem in default checked values with it. following is the code snippet...
$result = db_query("SELECT nid, filepath FROM {content_type_brand}, {files} WHERE content_type_brand.field_brand_image_fid
= files.fid");
$items = array();
while ($r = db_fetch_array($result)) {
array_push($items, $r);
}
$options = array();
foreach( $items as $i ) {
$imagePath = base_path().$i['filepath'];
$options[$i['nid']] = '<img src="'.$imagePath.'"></img>';
}
$form['favorite_brands'] = array (
'#type' => 'fieldset',
'#title' => t('Favorite Brands'),
//'#weight' => 5,
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['favorite_brands']['brands_options']
= array(
'#type' => 'checkboxes',
'#options' => $options,
'#default_value' => $options_checked,// $options_checked is an array similar to $options but having elements which need to be checked by default...
'#multicolumn' => array('width' => 3)
);
but values are not checked by default... can anyone help what I am missing??
Thanks
Your $options_checked array should not be in the same format as your $options array. Your $options array contains nid => img tag pairs. Your $options_checked array should simply contain the nid values of the options that should be checked by default:
$options_checked = array(8,17);

Resources