issues with saveAssociated cakephp - cakephp

I'm having some issues trying to save an article that has 4 pictures. The thing is that i need to use the article id in order to name the pictures like article_id."-"$i
Since I have only 4 pictures per article this $i should be from 1 to 4 or from 0 to three.
Now the problem is that in order to achieve this i need to create and save Article model so i can have an id to use, but then after performing all the scripting to make the thumbs and form the names, when I go Article->saveAssociated() i have two times the article record created!! i tried to set the id to "-1" before saving but nothing...
Any suggestion will be very much appreciated !!!
Code:
public function add() {
if ($this->request->is ( 'ajax' )) {
$this->layout = 'ajax';
} else {
$this->layout = 'default';
}
if ($this->request->is ( 'post' )) {
$this->Article->create ();
$this->request->data ['Article'] ['time_stamp'] = date ( 'Y-m-d H:i:s', time () );
if ($this->Article->save($this->request->data) ) {
for ($i=0; $i<4; $i++){
$img_path = "./images/";
$extension[$i] = end(explode('.', $this->request->data['Image'][$i]['image']['name']));
$this->request->data['Image'][$i]['image'] = array('name'=>$this->Article->id."-".$i, 'tmp_name' => $this->request->data['Image'][$i]['image']['tmp_name']);
// $this->request->data['Image'][$i]['name'] = $this->Article->id."-".$i;
$this->request->data['Image'][$i]['ext']= $extension[$i];
$target_path[$i] = $img_path . basename($this->request->data['Image'][$i]['image']['name'].".".$extension[$i]);
if(!move_uploaded_file($this->request->data['Image'][$i]['image']['tmp_name'], $target_path[$i])) {
die(__ ( 'Fatal error, we are all going to die.' ));
}else{
$this->Resize->img($target_path[$i]);
$this->Resize->setNewImage($img_path.basename($this->request->data['Image'][$i]['image']['name']."t.".$extension[$i]));
$this->Resize->setProportionalFlag('H');
$this->Resize->setProportional(1);
$this->Resize->setNewSize(90, 90);
$this->Resize->make();
}
}
$this->Article->id;
pr($this->Article->id);
$this->Article->saveAssociated($this->request->data, array('deep' => true));
//$this->redirect ( array ('action' => 'view', $this->Article->id ) );
pr($this->Article->id);
exit;
$this->Session->setFlash ( __ ( 'Article "' . $this->request->data ["Article"] ["name"] . '" has been saved' ) );
} else {
$this->Session->setFlash ( __ ( 'The article could not be saved. Please, try again.' ) );
}
}
$items = $this->Article->Item->find ( 'list' );
$payments = $this->Article->Payment->find ( 'list' );
$shippings = $this->Article->Shipping->find ( 'list' );
$this->set ( compact ( 'items', 'payments', 'shippings' ) );
}

Instead of
$this->Article->saveAssociated();
which would save the Article AGAIN, just save the images separately using something like this:
foreach($this->request->data['Image'] as &$image) {
$image['name'] = 'whatever_you_want' . $this->Article->id;
$image['article_id'] = $this->Article->id;
}
$this->Article->Image->save($this->request->data['Image']);
Another option (not necessarily better - just another option) would just be to append the newly-created Article's id to the existing Article array, then saveAssociated(). If the Article has an id in it's data, it will update instead of create. I would suggest the first answer above, but - just brainstorming other options in case this helps for someone's scenario:
// 1) save the Article and get it's id
// 2) append the `id` into the Article array
// 3) do your image-name manipulation using the id
// 4) saveAssociated(), which updates the Article and creates the Images

Related

WP Custom Post Type - Display taxonomy as CSS class

I have set up a custom post type in wordpress called "Portfolio". The custom post type then has two taxonomy's set up. They are named 'portfolio_categories' and 'portfolio_sector'.
Currently i am using the following code to gather all my 'portfolio_categories' and store them so they can then be outputted as CSS class to be used for filtering.
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$termsArray = get_the_terms( $post->ID, "portfolio_categories" ); //Get the terms for this particular item
$termsString = ""; //initialize the string that will contain the terms
foreach ( $termsArray as $term ) { // for each term
$termsString .= $term->slug.' '; //create a string that has all the slugs
}
?>
Then the code to output the terms as classes is as follows:
<div class="<?php echo $termsString; ?>">
Content goes here
</div>
How would i need to edit my code in order to store the taxonomy 'portfolio_sector' and output them as classes also?
You should also get your others terms data, in your context
<?php
while ( $the_query->have_posts() ) {
$the_query->the_post();
$termsArray = get_the_terms( $post->ID, "portfolio_categories" ); //Get the terms for this particular item#
$termsSectors = get_the_terms( $post->ID, "portfolio_sector" );
$termsString = ""; //initialize the string that will contain the terms
foreach ( $termsSectors as $term ) { // for each term
$termsSector .= $term->slug.' '; //create a string that has all the slugs
}
foreach ( $termsArray as $term ) { // for each term
$termsString .= $term->slug.' '; //create a string that has all the slugs
}
}
Now you can echo this via the var $termsSector.
However, as a hint you can also work with get_the_term_list() to get a list include HTML. Maybe this is easier for you and it is not necessary to loop about the array of the terms.

Cakephp3 ElasticSearch - How to get results

How do I get Data in Array format from a 'find('all')' call.
$query->all ()->getResponse ()->getData ()['message']
gives me a json string '{\"_source[]....}'
Below is my code sample
use Cake\ElasticSearch\TypeRegistry;
class PagesController extends AppController {
public function index() {
$english_pages = TypeRegistry::get ( 'EnglishPages' );
$query = $english_pages->find ( 'all' );
// $query = $query->getData();
// $query->all () ;
// $query->all ()->getResponse () );
// json_decode ( stripslashes($query->all ()->getResponse ()->getData ()['message']) , true ) ;
// echo json_last_error_msg ();
// json_encode ( $query->all ()->getResponse ()->getData ()['message'] ) ;
}
}
The Cakephp docs are not inline with the current Cakephp3 Elastic search on Github.
It works the same as using the ORM:
$query = $english_pages->find('all');
$results = $query->toArray();

How do you filter Joomla 3 articles by article id

I'm trying to create a Joomla module that displays articles based on categories and tags.
I've taken code for selecting tagged articles from https://github.com/lasinducharith/joomla-tags-selected) and introduced it into a copy of mod_articles_news:
public static function getList(&$params)
{
$app = JFactory::getApplication();
$db = JFactory::getDbo();
// Code base on https://github.com/lasinducharith/joomla-tags-selected to fetch ids of tagged articles
$tagsHelper = new JHelperTags;
$tagIds = $params->get('tagid', array());
$tagIds = implode(',', $tagIds);
echo '<pre>search for tags[' . $tagIds . ']';
$query=$tagsHelper->getTagItemsQuery($tagIds, $typesr = null, $includeChildren = false, $orderByOption = 'c.core_title', $orderDir = 'ASC',$anyOrAll = true, $languageFilter = 'all', $stateFilter = '0,1');
$db->setQuery($query, 0, $maximum);
$results = $db->loadObjectList();
$article_ids=array();
foreach ($results as $result){
$article_ids[]=$result->content_item_id;
}
echo ' yields articles[' . implode(',', $article_ids ) . ']</pre>';
// Get an instance of the generic articles model
$model = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
// Set application parameters in model
$appParams = JFactory::getApplication()->getParams();
$model->setState('params', $appParams);
// Set the filters based on the module params
$model->setState('list.start', 0);
$model->setState('list.limit', (int) $params->get('count', 15));
$model->setState('filter.published', 1);
$model->setState('list.select', 'a.fulltext, a.id, a.title, a.alias, a.introtext, a.state, a.catid, a.created, a.created_by, a.created_by_alias,' .
' a.modified, a.modified_by, a.publish_up, a.publish_down, a.images, a.urls, a.attribs, a.metadata, a.metakey, a.metadesc, a.access,' .
' a.hits, a.featured' );
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$model->setState('filter.access', $access);
// Category filter
$model->setState('filter.category_id', $params->get('catid', array()));
// Article filter
$model->setState('filter.id', $article_ids);
// Filter by language
$model->setState('filter.language', $app->getLanguageFilter());
// Set ordering
$ordering = $params->get('ordering', 'a.publish_up');
$model->setState('list.ordering', $ordering);
if (trim($ordering) == 'rand()')
{
$model->setState('list.direction', '');
}
else
{
$direction = $params->get('direction', 1) ? 'DESC' : 'ASC';
$model->setState('list.direction', $direction);
}
// Retrieve Content
$items = $model->getItems();
$newitems=array();
foreach ($items as &$item)
{
echo '<pre>fetched article[' . $item->id .'] which is ';
if ( !in_array($item->id, $article_ids )){
echo 'not tagged';
} else{
echo 'tagged';
}
echo '</pre>';
...
}
return $newitems;
}
The debug statements give me:
search for tags[2] yields articles[40,44,45]
fetched article[45] which is tagged
fetched article[44] which is tagged
fetched article[43] which is not tagged
fetched article[42] which is not tagged
fetched article[41] which is not tagged
fetched article[40] which is tagged
fetched article[39] which is not tagged
fetched article[38] which is not tagged
So the articles have not been filtered by id. I'd be very grateful for any advice.
Thanks
Found the problem, the filter should be article_id:
// Article filter
$model->setState('filter.article_id', $article_ids);
Now it selects articles based on tags and categories

Save id of post to the new table in Wordpress

I created a new table(new_table) in the Database.
I need, when I am adding a new post, id this post will save to my table(new_table.p_id).
How can do it?
Use the wpdb class's insert method.
First parameter is the table you want to insert data into. The second is an array containing the data in key value pairs.
Hook this into save_post.
function wpse_add_new_post_id_to_table( $post_id ) {
global $wpdb;
$post_status = get_post_status( $post_id );
if ( 'publish' != $post_status )
return false;
$wpdb->insert( 'new_table', array( 'p_id' => $post_id ) );
}
add_action( 'wp_insert_post', 'wpse_add_new_post_id_to_table' );
Further reading:
http://codex.wordpress.org/Plugin_API/Action_Reference/wp_insert_post
http://codex.wordpress.org/Class_Reference/wpdb
You use something like this action
function insert_id_to_db() {
global $post;
$postid = $post->id;
$wpdb->query("INSERT INTO table(id) VALUES('{$postid }')");
}
add_action('save_post', 'insert_id_to_db');

How do I use fixed fields in CakeDC's csvUpload behavior in Util plugin

I am using the csvUpload behavior of the Utils plugin by CakeDC, on a CakePHP 2.2.1 install.
I have it working great it's processing a rather large csv successfully. However there are two fields in my table / Model that would be considered fixed, as they are based on ID's from from associated models that are not consistent. So I need to get these fixed values via variables which is easy enough.
So my question is, how do I use the fixed fields aspect of csvUpload? I have tried that following and many little variation, which obviously didn't work.
public function upload_csv($Id = null) {
$unique_add = 69;
if ( $this->request->is('POST') ) {
$records_count = $this->Model->find( 'count' );
try {
$fixed = array('Model' => array('random_id' => $Id, 'unique_add' => $unique_add));
$this->Model->importCSV($this->request->data['Model']['CsvFile']['tmp_name'], $fixed);
} catch (Exception $e) {
$import_errors = $this->Model->getImportErrors();
$this->set( 'import_errors', $import_errors );
$this->Session->setFlash( __('Error Importing') . ' ' . $this->request->data['Model']['CsvFile']['name'] . ', ' . __('column name mismatch.') );
$this->redirect( array('action'=>'import') );
}
$new_records_count = $this->Model->find( 'count' ) - $records_count;
$this->Session->setFlash(__('Successfully imported') . ' ' . $new_records_count . ' records from ' . $this->request->data['Model']['CsvFile']['name'] );
$this->redirect(array('plugin'=>'usermgmt', 'controller'=>'users', 'action'=>'dashboard'));
}
}
Any help would be greatly appreciated as I have only found 1 post concerning this behavior when I searching...
I made my custom method to achieve the same task. Define the following method in app\Plugin\Utils\Model\Behavior
public function getCSVData(Model &$Model, $file, $fixed = array())
{
$settings = array(
'delimiter' => ',',
'enclosure' => '"',
'hasHeader' => true
);
$this->setup($Model, $settings);
$handle = new SplFileObject($file, 'rb');
$header = $this->_getHeader($Model, $handle);
$db = $Model->getDataSource();
$db->begin($Model);
$saved = array();
$data = array();
$i = 0;
while (($row = $this->_getCSVLine($Model, $handle)) !== false)
{
foreach ($header as $k => $col)
{
// get the data field from Model.field
$col = str_replace('.', '-', trim($col));
if (strpos($col, '.') !== false)
{
list($model,$field) = explode('.', $col);
$data[$i][$model][$field] = (isset($row[$k])) ? $row[$k] : '';
}
else
{
$col = str_replace(' ','_', $col);
$data[$i][$Model->alias][$col] = (isset($row[$k])) ? $row[$k] : '';
}
}
$is_valid_row = false;
foreach($data[$i][$Model->alias] as $col => $value )
{
if(!empty($data[$i][$Model->alias][$col]))
{
$is_valid_row = true;
}
}
if($is_valid_row == true)
{
$i++;
$data = Set::merge($data, $fixed);
}
else
{
unset($data[$i]);
}
}
return $data;
}
And you can use it using:
$csv_data = $this->Model->getCSVData($this->request->data['Model']['CsvFile']['tmp_name'], $fixed);
Here $csv_data will contain an array of all of those records from the csv file which are not empty and with the fixed field in each record index.
So as I was telling Arun, I answered my own question and figured it out. I was looking to broad instead of really examining what was in front of me. I started running some debugging and figured it out.
First of all, $unique_add = 69 is seen as an int, duh. In order for it to be added to the csv it need to viewed as a string. So it simply becomes, $unique_add = '69'.
I couldn't enter the value of $Id directly into the fixed array. So I just had to perform a simple find to get the value I needed.
$needed_id = $this->Model->find('first', array(
'condition'=>array('Model.id'=>$Id)
)
);
$random_id = $needed_id['Model']['id'];
Hopefully this won't be needed to help anyone because hopefully no one else will make this silly mistake. But one plus... Now there's actually more than one post on the internet documenting the use of fixed fields in the CakeDC Utils plugin.

Resources