Change default members tab to popular in elgg - php

I'm writing a plugin in elgg to change default tab of elgg members to popular instead of newest in members list. But there is a problem. As I set default tab to popular then newest tab not working anymore.
here is my start.php file:
<?php
elgg_register_event_handler('init', 'system', 'plug_test_init');
function plug_test_init(){
elgg_unregister_page_handler('members');
elgg_register_page_handler('members', 'set_popular_as_default');
}
function set_popular_as_default($page) {
if (empty($page[0])) {
$page[0] = 'popular';
}
if ($page[0] == 'search') {
echo elgg_view_resource('members/search');
} else {
echo elgg_view_resource('members/index', [
'page' => $page[0],
]);
}
return true;
}

Thanks to iionly in elgg community, in this discussion The problem solved by a using hooks of members:
<?php
elgg_register_event_handler('init', 'system', 'plug_test_init');
function plug_test_init(){
elgg_unregister_plugin_hook_handler('members:config', 'tabs', "members_nav_newest");
elgg_register_plugin_hook_handler('members:config', 'tabs', "my_members_nav_newest");
elgg_unregister_page_handler('members');
elgg_register_page_handler('members', 'set_popular_as_default');
}
function set_popular_as_default($page) {
if (empty($page[0])) {
$page[0] = 'popular';
}
if ($page[0] == 'search') {
echo elgg_view_resource('members/search');
} else {
echo elgg_view_resource('members/index', [
'page' => $page[0],
]);
}
return true;
}
function my_members_nav_newest($hook, $type, $returnvalue, $params) {
$returnvalue['newest'] = array(
'title' => elgg_echo('sort:newest'),
'url' => "members/newest",
);
return $returnvalue;
}

Related

How can fixup dbforge problem in codeigniter -4

When I am trying to insert new column using codeigniter version 4 with dbforge.
I got an error in Production mode:
Whoops!We seem to have hit a snag. Please try again later...
public function addLanguage()
{
$language = preg_replace('/[^a-zA-Z0-9_]/', '', $this->request->getPost('language',FILTER_SANITIZE_STRING));
$language = strtolower($language);
if (!empty($language)) {
if (!$this->db->fieldExists($language, "language")) {
$this->dbforge->addColumn("language", [
$language => [
'type' => 'TEXT'
]
]);
$this->session->setFlashdata('message', 'Language added successfully');
return redirect()->route('backend/setting/language');
}
} else {
$this->session->setFlashdata('exception', display('please_try_again'));
}
return redirect()->route('backend/setting/language');
}
What am I doing wrong in this code? Any potential help would be greatly appreciated!
Development mode error image below:
You can use this code
public function addLanguage()
{
$dbforge = \Config\Database::forge();
$language = preg_replace('/[^a-zA-Z0-9_]/', '', $this->request->getPost('language',FILTER_SANITIZE_STRING));
$language = strtolower($language);
if (!empty($language)) {
if (!$this->db->fieldExists($language, "language")) {
$dbforge->addColumn("language", [
$language => [
'type' => 'TEXT'
]
]);
$this->session->setFlashdata('message', 'Language added successfully');
return redirect()->route('backend/setting/language');
}
} else {
$this->session->setFlashdata('exception', display('please_try_again'));
}
return redirect()->route('backend/setting/language');
}

How to use REST with MVC when there is no Database?

I have two servers, the first works using REST and other Webs pages that are built using MVC.
I usually always run REST commands in the Controller layer, however I am with a doubt, assuming that my project (using MVC) does not use database and I'm using Controllers only to send commands to the webservice to send and receive information.
The REST this case would be the like Model?
In this case I should call the Rest within the Controllers and not create Models. eg .:
public function createProductAction() {
$rest = Rest('ws.example.com', 'PUT /items/', array(
'price' => $price,
'description' => $descricao
));
if ($response->status === 200) {
View::show('success.tpl');
} else {
View::show('error.tpl', $rest->error());
}
}
public function viewProductAction() {
$rest = Rest('ws.example.com', 'GET /items/{id}', array(
'id' => $_GET['id']
));
$response = json_decode($rest->getRespose());
if ($response->status() === 200) {
View::show('product.tpl', $response);
} else {
View::show('error.tpl', $rest->error());
}
}
or
I would have to create Models to make the calls to REST?
For example:
class ProductsModel
{
public function putItem($preco, $descricao)
{
$rest = Rest('ws.example.com', 'PUT /items/', array(
'price' => $price,
'description' => $descricao
));
//If status=200 new product is added
return $response->status() === 200;
}
public function deleteItem($id)
{
$rest = Rest('ws.example.com', 'DELETE /items/{id}', array(
'id' => $id
));
//If status=200 product is deleted
return $rest->status() === 200;
}
public function getItem($id)
{
$rest = Rest('ws.example.com', 'GET /items/{id}', array(
'id' => $id
));
if ($rest->status() === 200) {
//If status=200 return data
return json_decode($rest->getRespose());
}
return NULL;
}
}
How should I proceed?

CakePHP 2.0, Submit form redirect not rendering properly

Hi I've created a file upload form, it all works perfectly apart from when I press submit it does not re-direct me to the Uploads/add.ctp, but it does save the file to the directory and on to the database.In fact if I point the re-direct to uploads/browse it still does not take me to uploads/browse.
This is my controller
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)){
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4')) {
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
$this->redirect(array('controller'=>'Uploads','action' => 'add'));
} else{
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
}
and this is my form
<div class="maincontent">
<?php echo $this->Form->create('Upload', array('type' => 'file', 'class'=>'uploadfrm'));?>
<fieldset class='registerf'>
<legend class='registerf2'>Upload a Video</legend>
<?php
echo 'Upload your video content here, there is no size limit however it is <b>.mp4</b> file format only.';
echo '<br/>';
echo '<br/>';
echo $this->Form->input('name', array('between'=>'<br />', 'class'=>'input'));
echo $this->Form->input('eventname', array('between'=>'<br />'));
echo $this->Form->input('description', array('between'=>'<br />', 'rows'=> '7', 'cols'=> '60'));
echo $this->Form->hidden('userid', array('id' => 'user_id','value' => $auth['id']));
echo $this->Form->hidden('username', array('id' => 'username', 'value' => $auth['username']));
echo $this->Form->input('file', array('type' => 'file'));
echo "<br/>"
?>
<?php echo $this->Form->end(__('Submit', true));?>
</fieldset>
<?php
class UploadsController extends AppController {
public $name = 'Uploads';
public $helpers = array('Js');
// Users memeber area, is User logged in…
public $components = array(
'Session',
'RequestHandler',
'Auth'=>array(
'loginRedirect'=>array('controller'=>'uploads', 'action'=>'browse'),
'logoutRedirect'=>array('controller'=>'users', 'action'=>'login'),
'authError'=>"Members Area Only, Please Login…",
'authorize'=>array('Controller')
)
);
public function isAuthorized($user) {
// regular user can access the file uploads area
if (isset($user['role']) && $user['role'] === 'regular') {
return true;
}
// Default deny
return false;
}
function index() {
$this->set('users', $this->Upload->find('all'));
}
// Handling File Upload Function and updating uploads database
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK){
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4'))
{
$this->redirect(array('controller' => 'Uploads', 'action' => 'add'));
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
} }else {
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
function browse () {
// Find all in uploads database and paginates
$this->paginate = array(
'limit' => 5 ,
'order' => array(
'name' => 'asc'
)
);
$data = $this->paginate('Upload');
$this->set(compact('data'));
}
function recentuploads () {
$uploads = $this->Upload->find('all',
array('limit' =>7,
'order' =>
array('Upload.date_uploaded' => 'desc')));
if(isset($this->params['requested'])) {
return $uploads;
}
$this->set('uploads', $uploads);
}
function watch ($id = null){
$this->set('isAjax', $this->RequestHandler->isAjax());
// Read Uploads Table to watch video
$this->Upload->id = $id;
$this->set('uploads', $this->Upload->read());
// Load Posts Model for comments related to video
$this->loadModel('Post');
$this->paginate = array(
'conditions' => array(
'uploadid' => $id),
'limit' => 4
);
$data = $this->paginate('Post');
$this->set(compact('data'));
// Load Likes Model and retrive number of likes and dislikes
$this->loadModel('Like');
$related_likes = $this->Like->find('count', array(
'conditions' => array('uploadid' => $id)
));
$this->set('likes', $related_likes);
}
}
?>
Any suggestions?
This add function is in your UploadsController, correct? And you want it to redirect to uploads/browse?
In your UploadsController, what is $name set to?
<?php
class UploadsController extends AppController {
public $name = ?; // What is this variable set to?
}
By Cake's Inflector, when you specify controllers in a redirect, it should be lowercase:
$this->redirect(array('controller' => 'uploads', 'action' => 'browse'));
Or if the action you direct from and the action you want to direct to are in the same controller, you do not even need to specify the controller. For example if you submit the form from UploadsController add() and you want to redirect to browse():
$this->redirect(array('action' => 'browse'));
Try that and see if it helps.
Also note that you are calling $this->Upload->save($this->data) twice in your add function.
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)) {
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4')) {
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
$this->redirect(array('controller'=>'Uploads','action' => 'add'));
} else {
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
}
Specifically, here:
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)) {
$this->Upload->save($this->data);
...
When you call it in the if condition, it still saves the data to the database. It is fine to remove the second one.
If I add the following line in the function add
$this->render();
everything works perfectly, I'm struggling for the life of me to work out why I have to render the view if surely all other views are rendered by default.
But anyway got it working!
Hope this helps others :)

CakePHP 2.x Translate Behavior Not Saving to i18n Table

I've followed the instructions in the manual for setting up Translate Behavior with CakePHP 2.1, as well as this question here on Stack. I am not getting any errors, but my translated posts are not saving to my i18n table.
Here is my PostModel.php:
class Post extends AppModel {
public $title = 'Post';
public $name = 'Post';
public $body = 'Post';
public $actAs = array(
'Translate' => array(
'title' => 'titleTranslation',
'body' => 'bodyTranslation'
)
);
public $validate = array(
'title' => array(
'rule' => 'notEmpty'
),
'body' => array(
'rule' => 'notEmpty'
)
);
}
And here are my add and edit functions in PostsController.php:
public function add() {
if ($this->request->is('post')) {
$this->Post->locale = 'fre';
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.', true));
$this->redirect(array('action' => 'admin'));
} else {
$this->Session->setFlash(__('Unable to add your post.', true));
}
}
}
public function edit($id = null) {
$this->Post->id = $id;
if ($this->request->is('get'))
{
$this->Post->locale = 'fre';
$this->request->data = $this->Post->read();
}
else
{
if ($this->Post->save($this->request->data))
{
$this->Post->locale = 'fre';
$this->Session->setFlash(__('Your post has been updated.', true));
$this->redirect(array('action' => 'admin'));
}
else
{
$this->Session->setFlash(__('Unable to update your post.', true));
}
}
}
I initialized the i18n table using Console. Should I drop the table and try reinitializing? Not sure why there would be a problem there.
More reusable solution is to add to your AppModel:
class AppModel extends Model {
public $actsAs = array('Containable');
/**
* Converts structure of translated content by TranslateBehavior to be compatible
* when saving model
*
* #link http://rafal-filipek.blogspot.com/2009/01/translatebehavior-i-formularze-w.html
*/
public function afterFind($results, $primary = false) {
if (isset($this->Behaviors->Translate)) {
foreach ($this->Behaviors->Translate->settings[$this->alias] as $value) {
foreach ($results as $index => $row) {
if (array_key_exists($value, $row)) {
foreach($row[$value] as $locale) {
if (isset($results[$index][$this->alias][$locale['field']])) {
if (!is_array($results[$index][$this->alias][$locale['field']])) {
$results[$index][$this->alias][$locale['field']] = array();
}
$results[$index][$this->alias][$locale['field']][$locale['locale']] = $locale['content'];
}
}
}
}
}
}
return $results;
}
}
This code automatically converts what returns TranslateBehavior to be able to create multi-language form like:
echo $this->Form->input('Category.name.eng');
echo $this->Form->input('Category.name.deu');
echo $this->Form->input('Category.name.pol');
Tested on CakePHP 2.3. And I discovered that now Model->saveAssociated() is required instead of Model->save().
Try to add this in your form on add.ctp:
<?php
echo $this->Form->create('Post');
echo $this->Form->input('Post.title.fre');
echo $this->Form->input('Post.body.fre');
//Something more...
echo $this->Form->end(__('Submit'));
?>
in your edit.ctp:
<?php
echo $this->Form->create('Post');
echo $this->Form->input('id');
echo $this->Form->input('Post.title.fre', array('value'=>$this->request->data['titleTranslation'][0]['content'));
echo $this->Form->input('Post.body.fre', array('value'=>$this->request->data['bodyTranslation'][0]['content'));
//Something more...
echo $this->Form->end(__('Submit'));
?>
assuming index of data['titleTranslation'][0] is in French, to easily see an array in the view I recommend to use DebugKit https://github.com/cakephp/debug_kit
I hope this will help
Use saveMany instedof save. it's working fine for me.
For those who have the same problem: the correct variable is $actsAs, not $actAs.

PyroCMS/Codeigniter database issue

I may well be missing something quite obvious, but I'm still a bit lost. The actual database interaction seems to be the catch. I mean, the table is created on installation, but actually sending the information doesn't seem to work as it triggers the validation regardless of what I enter. If I turn off the field requirements, the database fails to receive the information entirely.
From the controller:
class Admin extends Admin_Controller
{
private $show_validation_rules = array(
array(
'field' => 'date',
'label' => 'Date',
'rules' => 'trim|max_length[100]|required'
),
array(
'field' => 'location',
'label' => 'Location',
'rules' => 'trim|max_length[300]'
),
array(
'field' => 'support',
'label' => 'Support',
'rules' => 'trim|required'
)
);
public function __construct()
{
parent::__construct();
$this->load->model('shows_m');
$this->load->library('form_validation');
$this->lang->load('shows');
$this->load->helper('html');
$this->template->set_partial('shortcuts', 'admin/partials/shortcuts');
}
public function index()
{
$view_data = array();
$view_data['shows'] = $this->shows_m->get_all();
$this->template->build('admin/index', $view_data);
}
public function create()
{
$shows = $this->shows_m->get_all();
$this->form_validation->set_rules($this->show_validation_rules);
if ( $this->form_validation->run() )
{
if ($this->shows_m->insert_show($this->input->post()))
{
$this->session->set_flashdata('success', lang('shows.create_success'));
redirect('admin/shows/index');
} else {
$this->session->set_flashdata('error', lang('shows.create_error'));
redirect('admin/shows/create');
}
}
foreach($this->show_validation_rules as $rule)
{
$shows[$rule['field']] = $this->input->post($rule['field']);
}
$view_data = array(
'shows' => $shows
);
$this->template->build('admin/create', $view_data);
}
public function edit($id)
{
$this->form_validation->set_rules($this->show_validation_rules);
$show = $this->shows_m->get($id);
if ( empty($show) )
{
$this->session->set_flashdata('error', lang('shows.exists_error'));
redirect('admin/shows');
}
if ( $this->form_validation->run() )
{
if ( $this->shows_m->update_entry($id, $this->input->post()) === TRUE )
{
if ( isset($this->input->post()['delete']) )
{
$this->session->set_flashdata('success', lang('shows.delete_success'));
redirect('admin/shows/');
}
else
{
$this->session->set_flashdata('success', lang('shows.update_success'));
redirect('admin/shows/edit/' . $id);
}
} else {
if ( isset($this->input->post()['delete']) )
{
$this->session->set_flashdata('error', lang('shows.delete_error'));
redirect('admin/shows/edit/' . $id);
}
else
{
$this->session->set_flashdata('error', lang('shows.update_error'));
redirect('admin/shows/edit/' . $id);
}
}
}
foreach($this->show_validation_rules as $rule)
{
if ($this->input->post($rule['field']))
{
$show[$rule['field']] = $this->input->post($rule['field']);
}
}
$view_data = array(
'shows' => $show
);
$this->template->build('admin/edit', $view_data);
}
public function delete($id = NULL)
{
$id_array = array();
if ( $this->input->post() )
{
$id_array = $this->input->post()['action_to'];
}
else
{
if ( $id !== NULL )
{
$id_array[0] = $id;
}
}
if ( empty($id_array) )
{
$this->session->set_flashdata('error', lang('shows.id_error'));
redirect('admin/shows');
}
foreach ( $id_array as $id)
{
$show = $this->shows_m->get($id);
if ( !empty($show) )
{
if ( $this->shows_m->delete($id) == FALSE )
{
$this->session->set_flashdata('error', lang('shows.delete_error'));
redirect('admin/shows');
}
}
}
$this->session->set_flashdata('success', lang('shows.delete_success'));
redirect('admin/shows');
}
}
From the details.php file
public function install()
{
$this->dbforge->drop_table('shows');
$shows = "
CREATE TABLE ".$this->db->dbprefix('shows')." (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` varchar(100) NOT NULL,
`location` varchar(300) NOT NULL,
`support` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
";
if($this->db->query($shows))
{
return TRUE;
}
}
The intent of the module is, in short to output the date of the show, the location and any supporting bands and other info by inserting a tag produced by the module in to the pertinent page on the site.
I'm inclined to think it should be quite simple and that I'm missing something obvious, but who knows. If I am, feel free to yell at me, I'd appreciate it.
Edit:
Code for the model
class Shows_m extends MY_Model {
public function get_all($limit = NULL)
{
$this->db->order_by("id", "desc");
if (isset($limit)){ $this->db->limit($limit); }
$results = $this->db->get('shows');
$result = $results->result_array();
return $result;
}
public function get($id)
{
$results = $this->db->get_where('shows', array('id' => $id));
$result = $results->row_array();
return $result;
}
public function insert_show($input)
{
$to_insert = array(
'date' => $input['date'],
'location' => $input['location'],
'support' => $input['support']
);
if ($this->db->insert('shows',$to_insert))
{
return TRUE;
} else {
return FALSE;
}
}
public function update_entry($id, $input)
{
$new_data = array(
'date' => $input['date'],
'location' => $input['location'],
'support' => $input['support']
);
if (isset ($input['delete']) )
{
if($this->delete($id))
{
return TRUE;
} else {
return FALSE;
}
} else {
$this->db->where('id', $id);
if ($this->db->update('shows', $new_data))
{
return TRUE;
} else {
return FALSE;
}
}
}
public function delete($id)
{
if ($this->db->delete('shows', array('id' => $id)))
{
return TRUE;
} else {
return FALSE;
}
}
}
It might be your insert in the model
if ($this->db->insert('shows',$to_insert))
{
return TRUE;
} else {
return FALSE;
}
Try instead:
$this->db->insert('shows',$to_insert);
$query_result = $this->db->insert_id();
if($query_result){
return TRUE;
}else{
return FALSE;
}
I don't think insert returns anything.
At any rate, it doesn't sound like validation is the problem. The query isn't getting to the db. If the above isn't the issue, try just echoing out the POST data; make sure it's getting to the model (make sure the HTML is as expected--input names and such).

Categories