Checkboxlist boxes won't appear checked on Update page - php

I have a checkboxlist on both create and update views:
<?php echo $form->field($model3, 'options[]')->checkboxList(['CPF' => 'CPF', 'FWL' => 'FWL', 'SDL' => 'SDL', 'CDAC' => 'CDAC']); ?>
Then I used this code to save the checkboxlist checked boxes as strings:
$model3->options = implode(',', $model3->options);
Upon updating, I used this code to convert it back to an array:
$model3->options = explode(",", $model3->options);
I expect that there should be checked boxes in my update page based on what's checked upon creation. But the checkboxlist boxes remain unchecked.
Here's my controller:
public function actionCreateNewStaff()
{
$session = Yii::$app->session;
if($session['user_type']=='SuperAdmin'){
$model1 = new User();
$model2 = new UserModule();
$model3 = new Employee();
if($model1->load(Yii::$app->request->post()) && $model2->load(Yii::$app->request->post()) && $model3->load(Yii::$app->request->post())){
$model1->user_type = 'BizStaff';
$model1->status = 1;
date_default_timezone_set('Asia/Manila');
$model1->date_added = date('Y/m/d', time());
$model1->avatar = UploadedFile::getInstance($model1, 'avatar');
$model1->creator_id = Yii::$app->user->identity->_id;
$model1->parent = $session['store_owner'];
$model1->password = sha1($model1->password);
if($model1->save()){
$model2->user_id = $model1->_id;
$model2->save();
$model3->user_id = $model1->_id;
if(isset($model3->options)){
$model3->options = implode(',', $model3->options);
}
$model3->save();
Yii::$app->session->setFlash('success', "Success!");
}
else{
Yii::$app->session->setFlash('error', "User Registration Failed!");
}
return $this->redirect(['managestaff']);
} else {
return $this->renderAjax('createstaff', [
'model1' => $model1,
'model2' => $model2,
'model3' => $model3,
]);
}
}else{
return $this->goHome();
}
}
public function actionUpdateEmployee($id)
{
$session = Yii::$app->session;
$model1 = $this->findModel($id);
$password = $model1->password;
$model2 = UserModule::find()->where( [ 'user_id' => new \MongoId($id) ] )->one();
$model3 = Employee::find()->where( [ 'user_id' => new \MongoId($id) ] )->one();
if(isset($model3->options)){
$model3->options = explode(",", $model3->options);
}
$username = $model1->username;
if($model1->load(Yii::$app->request->post()) && $model2->load(Yii::$app->request->post()) && $model3->load(Yii::$app->request->post())) {
if($model1->password != $password)
$model1->password = sha1($model1->password);
else
$model1->password = $password;
date_default_timezone_set('Asia/Manila');
$model1->date_added = date('Y/m/d', time());
$model1->save();
if($model1->save()){
$model2->user_id= $model1->_id;
$count = count($session['modules']);
foreach($session['modules'] as $module){
if(is_int($model2->{$module})){
$model2->{$module} = null; //unchecked
}
else{
$model2->{$module}= '1'; //checked
}
}
$model2->save();
if(isset($model3->options)){
$model3->options = implode(',', $model3->options);
}
$model3->save();
Yii::$app->session->setFlash('success', "User successfully updated!");
return $this->redirect(['viewemployee', 'id' => (string)$model1->_id]);
}
} else {
return $this->render('updateemployee', [
'model1' => $model1,
'model2' => $model2,
'model3' => $model3,
]);
}
}
How do I display these checked boxes on my update page?

After some experimenting my guess is that you just have to change the attribute name in the ActiveField:
//from
<?php echo $form->field($model3, 'options[]')->checkboxList([....]); ?>
//to
<?php echo $form->field($model3, 'options')->checkboxList([....]); ?>
I hope this is correct. What you also should do is on imploding:
$model3->options = empty($model3->options) ? '' : implode(',', $model3->options);
Since it could be that no checkbox is selected. Then an empty string will be sent to the server.

Related

Yii2 getting the url ID in redirect. in create action

like I have a view index.php(Gridview)- linked to a Menu Manage Instructor.
from there I click on edit for a specific instructor.
The URL I get is like:
admin/user/update-instructor?id=11
In this page I have multiple tabs, one tab is instructor_schedule, which is again a grid view with add records button on top.
I can add records clicking on add record without any issue.
My problem is now I want the form page redirect back to the page
admin/user/update-instructor?id=11
How I can achieve that?
I have tried like:
return $this->redirect(['user/update-instructor','id' => $model->id]);
and
return $this->redirect(['user/update-instructor','id' => $model->instructor_id]);
but I am getting the error missing information id.
Thanks.
action Create(ClassDurationController):
public function actionCreate() {
$model = new ClassDuration();
$count = count(Yii::$app->request->post('ClassDuration', []));
$classdurations[] =new ClassDuration();
for($i = 1; $i < $count; $i++) {
$classdurations[] = new ClassDuration();
}
//if ($model->load(Yii::$app->request->post()) && $model->save()) {
if (Model::loadMultiple($classdurations, Yii::$app->request->post()) && Model::validateMultiple($classdurations)) {
foreach ($classdurations as $classduration) {
// var_dump($classdurations);
$classduration->instructor_id=$_POST['ClassDuration'][0]['instructor_id'];
$classduration->save(false);
}
Yii::$app->getSession()->setFlash('successClass');
//return $this->redirect(['view', 'id' => $model->id]);
return $this->redirect(['user/update-instructor','id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
'classdurations' => $classdurations,
]);
}
Action Update(ClassDurationController):
public function actionUpdate($id,$tab='information') {
$model = $this->findModel($id);
$wd_instructor = ClassDuration::find('instructor_id')->where(['id'=>$id])->One();
$wd_instructor_id = $wd_instructor->instructor_id;
$classdurations = ClassDuration::find()->where(['instructor_id'=>$wd_instructor_id])->all();
if (Model::loadMultiple($classdurations, Yii::$app->request->post()) && Model::validateMultiple($classdurations)) {
foreach($classdurations as $classduration){
$classduration->location_id=$_POST['ClassDuration'][0]['location_id'];
$classduration->save(false);
}
Yii::$app->getSession()->setFlash('successClass');
// return $this->redirect(['view', 'id' => $model->id]);
return $this->redirect(['user/update-instructor', 'id' => $model->instructor_id, 'tab' => 'instructor_schedule']);
}
return $this->render('update', [
'model' => $model,
'workingdays' => $classdurations,
]);
}
ActionUpdateInstructor:
public function actionUpdateInstructor($id,$tab='information') {
$model = User::findOne($id);
$uploadPath = 'web/instructor/' . $id;
if (!file_exists($uploadPath)) {
mkdir($uploadPath);
}
$profile = Instructor::find()->where(['user_id' => $id])->one();
if ($profile) {
$instructor_profile = $profile;
} else {
$instructor_profile = new Instructor;
$instructor_profile->user_id = $id;
}
if ($id == 1) {
$cls = 'hide';
} else {
$cls = '';
}
$title = "Update";
$modelsRest = $model->rest;
$modelsBreakTime = $model->breakTime;
if (Yii::$app->request->isAjax && $model->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($model);
}
if (Yii::$app->request->isAjax && $instructor_profile->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($instructor_profile);
}
if ($model->load(Yii::$app->request->post()) && $instructor_profile->load(Yii::$app->request->post())) {
$oldIDs = ArrayHelper::map($modelsRest, 'id', 'id');
$modelsRest = Model::createMultiple(RestDays::classname(), $modelsRest);
Model::loadMultiple($modelsRest, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsRest, 'id', 'id')));
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ArrayHelper::merge(
ActiveForm::validateMultiple($modelsRest),
ActiveForm::validate($model),
ActiveForm::validate($instructor_profile)
);
}
if (trim($model->password) != '') {
$model->setPassword($model->password);
}
$model->username = $model->email;
$model->save();
if ($model->user_role != '') {
$assign = AuthAssignment::find()->where(['user_id' => $model->id])->One();
$assign->item_name = $model->user_role;
$assign->save();
}
$instructor_profile->file = UploadedFile::getInstance($instructor_profile, 'file');
$instructor_profile->user_id = $model->id;
if ($instructor_profile->file != '') {
$instructor_profile->instructor_image = time() . '.' . $instructor_profile->file->extension;
}
$instructor_profile->save(false);
if ($instructor_profile->file != '') {
$uploadPath = 'web/instructor/' . $instructor_profile->user_id;
if (!file_exists($uploadPath)) {
mkdir($uploadPath);
}
$instructor_profile->file->saveAs($uploadPath . '/' . $instructor_profile->instructor_image);
}
$valid = $model->validate();
$valid = Model::validateMultiple($modelsRest) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (!empty($deletedIDs)) {
RestDays::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsRest as $modelRests) {
$modelRests->instructor_id = $model->id;
if (!empty($modelRests->from_date) && !($flag = $modelRests->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
//return $this->redirect(['view-instructor', 'id' => $model->id]);
return $this->redirect(['instructor']);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
return $this->render('update_instructor', [
'model' => $model,
'modelsRest' => (empty($modelsRest)) ? [new RestDays] : $modelsRest,
'instructor_profile' => $instructor_profile,
'title' => $title,
'cls' => $cls,
]);
}
In your action Create(ClassDurationController) you assign to $model only
$model = new ClassDuration();
Maybe you should insert another variable to get id from parent or
return $this->redirect(['user/update-instructor','id' => $_POST['ClassDuration'][0]['instructor_id']]);

Yii2 inserting new record on update

I have a setup where for one of the Model I have repeat fields like user and userchildren
so userchildren have a set of fields like child_name, child_birth_date and child_gender
My controller code is like this:
public function actionUpdateProfile()
{
$user_id = Yii::$app->user->identity->id;
$model = User::find()->where(['id' => $user_id])->one();
$UserProfile = UserProfile::find()->where(['user_id' => $model->id])->one();
$userbillinginfo = UserBillingInfo::find()->where(['user_id' => $model->id])->one();
$userchildren = UserChildren::find()->where(['user_id' => $model->id])->all();
if ($userchildren) {
$profile = $UserProfile;
$billinginfo = $userbillinginfo;
$userchild = $userchildren;
} else {
$profile = new UserProfile;
$profile->user_id = $model->id;
$billinginfo = new UserBillingInfo;
$billinginfo->user_id = $model->id;
$userchild = New UserChildren;
$userchild->user_id = $model->id;
}
if (Yii::$app->request->isAjax && $model->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($model);
}
if (Yii::$app->request->isAjax && $profile->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($profile);
}
if (Yii::$app->request->isAjax && $billinginfo->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($billinginfo);
}
if (Yii::$app->request->isAjax && $userchild->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($userchild);
}
if ($model->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post()) && $billinginfo->load(Yii::$app->request->post())) {
$model->username = $model->email;
$model->save();
$profile->save();
$billinginfo->save();
if (!empty($_POST['UserChildren']) && !is_null($_POST['UserChildren'])) {
foreach ($_POST['UserChildren'] as $rows) {
$userchild = New UserChildren;
$userchild->attributes = $rows;
$userchild->user_id = $model->id;
$userchild->save();
}
}
return $this->redirect(['view']);
} else {
return $this->render('update-profile', [
'model' => $model,
'profile' => $profile,
'billinginfo' => $billinginfo,
'userchild' => $userchild,
]);
}
}
I am facing two issues:
first, when I go for an update of the profile the data is shown properly in the form, I can add records without any issue to the Model UserChildren
But if I edit an existing record it is inserting this as a new record, whereas I expect this to be updated.
I had this line of code like below:
,
if ($model->load(Yii::$app->request->post()) and
$profile->load(Yii::$app->request->post()) and
$billinginfo->load(Yii::$app->request->post()) and
$billinginfo->load(Yii::$app->request->post())
) {
...
but after I updated the line of code,
$userchildren = UserChildren::find()->where(['user_id' => $model->id])->one();
to
$userchildren = UserChildren::find()->where(['user_id' => $model->id])->all();
and thus had to modify the line like below:
if ($model->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post()) && $billinginfo->load(Yii::$app->request->post()) ) {
What I am missing here? Thanks.

How to set hit counter in yii

I'd like to make a hit counter that will add the count when user enter the website through their ip address. This is my code:
for views:
<?php echo number_format(Visitor::model()->GetAll('portal')); ?>
this is my model:
public function attributeLabels() {
return array(
'id' => 'ID',
'web' => 'Web',
'dtvisit' => 'Dtvisit',
'total' => 'Total',
);
}
public function AddVisitor($web) {
date_default_timezone_set('Asia/Kuala_Lumpur');
$today = date('Y-m-d');
$model = $this->findByAttributes(array('dtvisit' => $today, 'web' => $web));
if (sizeof($model) > 0) {
//update
$model2 = $this->findByPk($model->id);
$model2->total = (1 + $model->total);
$model2->save();
} else {
//add new
$model2 = new Visitor;
$model2->web = $web;
$model2->dtvisit = $today;
$model2->total = 1;
$model2->save();
}
}
public function GetAll($web) {
date_default_timezone_set('Asia/Kuala_Lumpur');
$model = $this->findAll(array("condition" => "web='$web'"));
$total = 0;
if (sizeof($model) > 0) {
foreach ($model as $row) {
$total+= (int) $row->total;
}
}
return $total;
}
CUrrently, the total will add everytime I refresh or click any links on my website. How to make it add the total only when new user enter the website. Thank you
I think you should use Params for passing value
public function GetAll($web) {
date_default_timezone_set('Asia/Kuala_Lumpur');
$model = $this->findAll(array("condition" => "web=':web'",
'params' => array(:web=$web)));
$total = 0;
if (sizeof($model) > 0) {
foreach ($model as $row) {
$total+= (int) $row->total;
}
}
return $total;
}

accessing 'blog' functionality / template in FUEL CMS

I'm having trouble getting the "stock" blog functionality / template working within FUEL CMS.
I have read that it is already there, stock with the download configuration of the CMS; I have also tried creating one from scratch and uploading a 'blog' theme from a project found in GitHub. None have worked so far.
I found the blog variable at:
_variables/global.php
I have created a 'blog' controller via interpretation of (gappy) docs.
By adding the below code within it; then making a corresponding 'blog.php' view. I get nothing but a 404 error.
<?php
class Blog extends CI_Controller {
public function view($page = 'home')
{
//you can acesse this http://example.com/blog/view/
}
public function new($page = 'home')
{
//you can acesse this http://example.com/blog/new/
}
}
Within the modules folder. I found this 'stock' blog controller file. But don't know how to use it? found at: /fuel/modules/blog/controller/blog.php
<?php
require_once(MODULES_PATH.'/blog/libraries/Blog_base_controller.php');
class Blog extends Blog_base_controller {
function __construct()
{
parent::__construct();
}
function _remap()
{
$year = ($this->uri->rsegment(2) != 'index') ? (int) $this->uri->rsegment(2) : NULL;
$month = (int) $this->uri->rsegment(3);
$day = (int) $this->uri->rsegment(4);
$slug = $this->uri->rsegment(5);
$limit = (int) $this->fuel->blog->config('per_page');
$view_by = 'page';
// we empty out year variable if it is page because we won't be querying on year'
if (preg_match('#\d{4}#', $year) && !empty($year) && empty($slug))
{
$view_by = 'date';
}
// if the first segment is id then treat the second segment as the id
else if ($this->uri->rsegment(2) === 'id' && $this->uri->rsegment(3))
{
$view_by = 'slug';
$slug = (int) $this->uri->rsegment(3);
$post = $this->fuel->blog->get_post($slug);
if (isset($post->id))
{
redirect($post->url);
}
}
else if (!empty($slug))
{
$view_by = 'slug';
}
// set this to false so that we can use segments for the limit
$cache_id = fuel_cache_id();
$cache = $this->fuel->blog->get_cache($cache_id);
if (!empty($cache))
{
$output =& $cache;
}
else
{
$vars = $this->_common_vars();
if ($view_by == 'slug')
{
return $this->post($slug);
}
else if ($view_by == 'date')
{
$page_title_arr = array();
$posts_date = mktime(0, 0, 0, $month, $day, $year);
if (!empty($day)) $page_title_arr[] = $day;
if (!empty($month)) $page_title_arr[] = date('M', strtotime($posts_date));
if (!empty($year)) $page_title_arr[] = $year;
// run before_posts_by_date hook
$hook_params = array('year' => $year, 'month' => $month, 'day' => $day, 'slug' => $slug, 'limit' => $limit);
$this->fuel->blog->run_hook('before_posts_by_date', $hook_params);
$vars = array_merge($vars, $hook_params);
$vars['page_title'] = $page_title_arr;
$vars['posts'] = $this->fuel->blog->get_posts_by_date($year, (int) $month, $day, $slug);
$vars['pagination'] = '';
}
else
{
$limit = $this->fuel->blog->config('per_page');
$this->load->library('pagination');
$config['uri_segment'] = 3;
$offset = $this->uri->segment($config['uri_segment']);
$this->config->set_item('enable_query_strings', FALSE);
$config = $this->fuel->blog->config('pagination');
$config['base_url'] = $this->fuel->blog->url('page/');
//$config['total_rows'] = $this->fuel->blog->get_posts_count();
$config['page_query_string'] = FALSE;
$config['per_page'] = $limit;
$config['num_links'] = 2;
//$this->pagination->initialize($config);
if (!empty($offset))
{
$vars['page_title'] = lang('blog_page_num_title', $offset, $offset + $limit);
}
else
{
$vars['page_title'] = '';
}
// run before_posts_by_date hook
$hook_params = array('offset' => $offset, 'limit' => $limit, 'type' => 'posts');
$this->fuel->blog->run_hook('before_posts_by_page', $hook_params);
$vars['offset'] = $offset;
$vars['limit'] = $limit;
$vars['posts'] = $this->fuel->blog->get_posts_by_page($limit, $offset);
// run hook again to get the proper count
$hook_params['type'] = 'count';
$this->fuel->blog->run_hook('before_posts_by_page', $hook_params);
//$config['total_rows'] = count($this->fuel->blog->get_posts_by_page());
$config['total_rows'] = $this->fuel->blog->get_posts_count();
// create pagination
$this->pagination->initialize($config);
$vars['pagination'] = $this->pagination->create_links();
}
// show the index page if the page doesn't have any uri_segment(3)'
$view = ($this->uri->rsegment(2) == 'index' OR ($this->uri->rsegment(2) == 'page' AND !$this->uri->segment(3))) ? 'index' : 'posts';
$output = $this->_render($view, $vars, TRUE);
$this->fuel->blog->save_cache($cache_id, $output);
}
$this->output->set_output($output);
}
function post($slug = null)
{
if (empty($slug))
{
redirect_404();
}
$this->load->library('session');
$blog_config = $this->fuel->blog->config();
// run before_posts_by_date hook
$hook_params = array('slug' => $slug);
$this->fuel->blog->run_hook('before_post', $hook_params);
$post = $this->fuel->blog->get_post($slug);
if (isset($post->id))
{
$vars = $this->_common_vars();
$vars['post'] = $post;
$vars['user'] = $this->fuel->blog->logged_in_user();
$vars['page_title'] = $post->title;
$vars['next'] = $this->fuel->blog->get_next_post($post);
$vars['prev'] = $this->fuel->blog->get_prev_post($post);
$vars['slug'] = $slug;
$vars['is_home'] = $this->fuel->blog->is_home();
$antispam = md5(random_string('unique'));
$field_values = array();
// post comment
if (!empty($_POST))
{
$field_values = $_POST;
// the id of "content" is a likely ID on the front end, so we use comment_content and need to remap
$field_values['content'] = $field_values['new_comment'];
unset($field_values['antispam']);
if (!empty($_POST['new_comment']))
{
$vars['processed'] = $this->_process_comment($post);
}
else
{
add_error(lang('blog_error_blank_comment'));
}
}
$cache_id = fuel_cache_id();
$cache = $this->fuel->blog->get_cache($cache_id);
if (!empty($cache) AND empty($_POST))
{
$output =& $cache;
}
else
{
$this->load->library('form');
if (is_true_val($this->fuel->blog->config('use_captchas')))
{
$captcha = $this->_render_captcha();
$vars['captcha'] = $captcha;
}
$vars['thanks'] = ($this->session->flashdata('thanks')) ? blog_block('comment_thanks', $vars, TRUE) : '';
$vars['comment_form'] = '';
$this->session->set_userdata('antispam', $antispam);
if ($post->allow_comments)
{
$this->load->module_model(BLOG_FOLDER, 'blog_comments_model');
$this->load->library('form_builder', $blog_config['comment_form']);
$fields['author_name'] = array('label' => 'Name', 'required' => TRUE);
$fields['author_email'] = array('label' => 'Email', 'required' => TRUE);
$fields['author_website'] = array('label' => 'Website');
$fields['new_comment'] = array('label' => 'Comment', 'type' => 'textarea', 'required' => TRUE);
$fields['post_id'] = array('type' => 'hidden', 'value' => $post->id);
$fields['antispam'] = array('type' => 'hidden', 'value' => $antispam);
if (!empty($vars['captcha']))
{
$fields['captcha'] = array('required' => TRUE, 'label' => 'Security Text', 'value' => '', 'after_html' => ' <span class="captcha">'.$vars['captcha']['image'].'</span><br /><span class="captcha_text">'.lang('blog_captcha_text').'</span>');
}
// now merge with config... can't do array_merge_recursive'
foreach($blog_config['comment_form']['fields'] as $key => $field)
{
if (isset($fields[$key])) $fields[$key] = array_merge($fields[$key], $field);
}
if (!isset($blog_config['comment_form']['label_layout'])) $this->form_builder->label_layout = 'left';
if (!isset($blog_config['comment_form']['submit_value'])) $this->form_builder->submit_value = 'Submit Comment';
if (!isset($blog_config['comment_form']['use_form_tag'])) $this->form_builder->use_form_tag = TRUE;
if (!isset($blog_config['comment_form']['display_errors'])) $this->form_builder->display_errors = TRUE;
$this->form_builder->form_attrs = 'method="post" action="'.site_url($this->uri->uri_string()).'#comments_form"';
$this->form_builder->set_fields($fields);
$this->form_builder->set_field_values($field_values);
$this->form_builder->set_validator($this->blog_comments_model->get_validation());
$vars['comment_form'] = $this->form_builder->render();
$vars['fields'] = $fields;
}
$output = $this->_render('post', $vars, TRUE);
// save cache only if we are not posting data
if (!empty($_POST))
{
$this->fuel->blog->save_cache($cache_id, $output);
}
}
if (!empty($output))
{
$this->output->set_output($output);
return;
}
}
else
{
show_404();
}
}
function _process_comment($post)
{
if (!is_true_val($this->fuel->blog->config('allow_comments'))) return;
$notified = FALSE;
// check captcha
if (!$this->_is_valid_captcha())
{
add_error(lang('blog_error_captcha_mismatch'));
}
// check that the site is submitted via the websit
if (!$this->_is_site_submitted())
{
add_error(lang('blog_error_comment_site_submit'));
}
// check consecutive posts
if (!$this->_is_not_consecutive_post())
{
add_error(lang('blog_error_consecutive_comments'));
}
$this->load->module_model(BLOG_FOLDER, 'blog_users_model');
$user = $this->blog_users_model->find_one(array('fuel_users.email' => $this->input->post('author_email', TRUE)));
// create comment
$this->load->module_model(BLOG_FOLDER, 'blog_comments_model');
$comment = $this->blog_comments_model->create();
$comment->post_id = $post->id;
$comment->author_id = (!empty($user->id)) ? $user->id : NULL;
$comment->author_name = $this->input->post('author_name', TRUE);
$comment->author_email = $this->input->post('author_email', TRUE);
$comment->author_website = $this->input->post('author_website', TRUE);
$comment->author_ip = $_SERVER['REMOTE_ADDR'];
$comment->content = trim($this->input->post('new_comment', TRUE));
$comment->date_added = NULL; // will automatically be added
//http://googleblog.blogspot.com/2005/01/preventing-comment-spam.html
//http://en.wikipedia.org/wiki/Spam_in_blogs
// check double posts by IP address
if ($comment->is_duplicate())
{
add_error(lang('blog_error_comment_already_submitted'));
}
// if no errors from above then proceed to submit
if (!has_errors())
{
// submit to akisment for validity
$comment = $this->_process_akismet($comment);
// process links and add no follow attribute
$comment = $this->_filter_comment($comment);
// set published status
if (is_true_val($comment->is_spam) OR $this->fuel->blog->config('monitor_comments'))
{
$comment->published = 'no';
}
// save comment if saveable and redirect
if (!is_true_val($comment->is_spam) OR (is_true_val($comment->is_spam) AND $this->fuel->blog->config('save_spam')))
{
if ($comment->save())
{
$notified = $this->_notify($comment, $post);
$this->load->library('session');
$vars['post'] = $post;
$vars['comment'] = $comment;
$this->session->set_flashdata('thanks', TRUE);
$this->session->set_userdata('last_comment_ip', $_SERVER['REMOTE_ADDR']);
$this->session->set_userdata('last_comment_time', time());
redirect($post->url);
}
else
{
add_errors($comment->errors());
}
}
else
{
add_error(lang('blog_comment_is_spam'));
}
}
return $notified;
}
// check captcha validity
function _is_valid_captcha()
{
$valid = TRUE;
// check captcha
if (is_true_val($this->fuel->blog->config('use_captchas')))
{
if (!$this->input->post('captcha'))
{
$valid = FALSE;
}
else if (!is_string($this->input->post('captcha')))
{
$valid = FALSE;
}
else
{
$post_captcha_md5 = $this->_get_encryption($this->input->post('captcha'));
$session_captcha_md5 = $this->session->userdata('comment_captcha');
if ($post_captcha_md5 != $session_captcha_md5)
{
$valid = FALSE;
}
}
}
return $valid;
}
// check to make sure the site issued a session variable to check against
function _is_site_submitted()
{
return ($this->session->userdata('antispam') AND $this->input->post('antispam') == $this->session->userdata('antispam'));
}
// disallow multiple successive submissions
function _is_not_consecutive_post()
{
$valid = TRUE;
$time_exp_secs = $this->fuel->blog->config('multiple_comment_submission_time_limit');
$last_comment_time = ($this->session->userdata('last_comment_time')) ? $this->session->userdata('last_comment_time') : 0;
$last_comment_ip = ($this->session->userdata('last_comment_ip')) ? $this->session->userdata('last_comment_ip') : 0;
if ($_SERVER['REMOTE_ADDR'] == $last_comment_ip AND !empty($time_exp_secs))
{
if (time() - $last_comment_time < $time_exp_secs)
{
$valid = FALSE;
}
}
return $valid;
}
// process through akisment
function _process_akismet($comment)
{
if ($this->fuel->blog->config('akismet_api_key'))
{
$this->load->module_library(BLOG_FOLDER, 'akismet');
$akisment_comment = array(
'author' => $comment->author_name,
'email' => $comment->author_email,
'body' => $comment->content
);
$config = array(
'blog_url' => $this->fuel->blog->url(),
'api_key' => $this->fuel->blog->config('akismet_api_key'),
'comment' => $akisment_comment
);
$this->akismet->init($config);
if ( $this->akismet->errors_exist() )
{
if ( $this->akismet->is_error('AKISMET_INVALID_KEY') )
{
log_message('error', 'AKISMET :: Theres a problem with the api key');
}
elseif ( $this->akismet->is_error('AKISMET_RESPONSE_FAILED') )
{
log_message('error', 'AKISMET :: Looks like the servers not responding');
}
elseif ( $this->akismet->is_error('AKISMET_SERVER_NOT_FOUND') )
{
log_message('error', 'AKISMET :: Wheres the server gone?');
}
}
else
{
$comment->is_spam = ($this->akismet->is_spam()) ? 'yes' : 'no';
}
}
return $comment;
}
// strip out
function _filter_comment($comment)
{
$this->load->helper('security');
$comment_attrs = array('content', 'author_name', 'author_email', 'author_website');
foreach($comment_attrs as $filter)
{
$text = $comment->$filter;
// first remove any nofollow attributes to clean up... not perfect but good enough
$text = preg_replace('/<a(.+)rel=["\'](.+)["\'](.+)>/Umi', '<a$1rel="nofollow"$3>', $text);
// $text = str_replace('<a ', '<a rel="nofollow"', $text);
$text = strip_image_tags($text);
$comment->$filter = $text;
}
return $comment;
}
function _notify($comment, $post)
{
// send email to post author
if (!empty($post->author))
{
$config['wordwrap'] = TRUE;
$this->load->library('email', $config);
$this->email->from($this->fuel->config('from_email'), $this->fuel->config('site_name'));
$this->email->to($post->author->email);
$this->email->subject(lang('blog_comment_monitor_subject', $this->fuel->blog->config('title')));
$msg = lang('blog_comment_monitor_msg');
$msg .= "\n".fuel_url('blog/comments/edit/'.$comment->id)."\n\n";
$msg .= (is_true_val($comment->is_spam)) ? lang('blog_email_flagged_as_spam')."\n" : '';
$msg .= lang('blog_email_published').": ".$comment->published."\n";
$msg .= lang('blog_email_author_name').": ".$comment->author_name."\n";
$msg .= lang('blog_email_author_email').": ".$comment->author_email."\n";
$msg .= lang('blog_email_author_website').": ".$comment->author_website."\n";
$msg .= lang('blog_email_author_ip').": ".gethostbyaddr($comment->author_ip)." (".$comment->author_ip.")\n";
$msg .= lang('blog_email_content').": ".$comment->content."\n";
$this->email->message($msg);
return $this->email->send();
}
else
{
return FALSE;
}
}
function _render_captcha()
{
$this->load->library('captcha');
$blog_config = $this->config->item('blog');
$assets_folders = $this->config->item('assets_folders');
$blog_folder = MODULES_PATH.BLOG_FOLDER.'/';
$captcha_path = $blog_folder.'assets/captchas/';
$word = strtoupper(random_string('alnum', 5));
$captcha_options = array(
'word' => $word,
'img_path' => $captcha_path, // system path to the image
'img_url' => captcha_path('', BLOG_FOLDER), // web path to the image
'font_path' => $blog_folder.'fonts/',
);
$captcha_options = array_merge($captcha_options, $blog_config['captcha']);
if (!empty($_POST['captcha']) AND $this->session->userdata('comment_captcha') == $this->input->post('captcha'))
{
$captcha_options['word'] = $this->input->post('captcha');
}
$captcha = $this->captcha->get_captcha_image($captcha_options);
$captcha_md5 = $this->_get_encryption($captcha['word']);
$this->session->set_userdata('comment_captcha', $captcha_md5);
return $captcha;
}
function _get_encryption($word)
{
$captcha_md5 = md5(strtoupper($word).$this->config->item('encryption_key'));
return $captcha_md5;
}
}
My goal is:
1.) Enable 'Blog' Module / template / functionality and understand how I did it. I find the docs lacking, I'm also new at code igniter so that could be why. I just want the most basic way to do this for now.
And 2.) I want to create a page 'from scratch' that resolves on the dashboard side as well. I have created pages in /views/ but they resolve with that whole string /fuel/application/views/page/ I want to create a normal page without all that in the URL. I have tried creating corresponding controllers even variables and haven't had much luck!!!!!!!
As of FUEL CMS 1.0 the blog module is no longer bundled with the CMS by default. You would need to do the following:
Download & setup FUEL CMS per the install instructions here: https://github.com/daylightstudio/FUEL-CMS
Next, once you've got that up and running you can download & setup the blog module per the instructions here: https://github.com/daylightstudio/FUEL-CMS-Blog-Module
Once the blog is setup, you should be able to access it at "yourdomain.com/blog". As far as creating themes, there is a views/themes folder in the blog module which contains a default theme and also where you can setup your custom theme. Additional information about the blog module & theming can be found here http://docs.getfuelcms.com/modules/blog

Variable button label

I got a form for the registration of a user and use it as an edit-user-form, too.
Now I want to make this form more vabiable. That means in my case: I want to have a specific button label for the different actions.
If the form is called via RegisterAction, the label should be "Register" and if it's called via EditAction, it shall be "Update user". I tried some things but now I ran out of ideas.
Here is my code:
CustomerController.php
...
public function registerAction(){
$form = new Application_Form_Register();
$request = $this->_request->getParams();
if(isset($request['registerbtn']) && ($form->isValid($request) )){
$customerModel = new Application_Model_Customer();
$customerArr = $customerModel->setCustomer($request,true);
$this->redirect('/customer/detail/id/'.$customerArr);
}
else{
$this->view->form = $form;
$this->view->button = "Register"; //TEST
}
}
public function editAction(){
$request = $this->_request->getParams();
if(isset($request['id']) && !empty($request['id'])){
$form = new Application_Form_Register();
$form->addElement('hidden', 'id', array(
'required' => true,
'value' => $request['id'],
'validators' => array(
$digits = new Zend_Validate_Digits()
)
));
if(isset($request['registerbtn']) && ($form->isValid($request) )){
$customerModel = new Application_Model_Customer();
$id = $customerModel->setCustomer($request,false);
$this->redirect('/customer/detail/id/'.$id);
}else{
$modelResult = new Application_Model_Customer();
$customer = $modelResult->getCustomer($request['id']);
$cArr = $customer->toArray();
$form->populate($cArr);
$this->view->form = $form;
$this->view->button = "Update user"; //TEST
}
}else{
$this->redirect('/');
}
}
...
The views
// register.phtml - begin
<h2>Registration</h2>
<?php
$this->headTitle('Registration');
$button = $this->button; //TEST
$this->form->button = $button; //TEST
echo $this->form;
echo $this->error;?>
// register.phtml - end
// edit.phtml - begin
<?php
echo $this->headline;
$this->headTitle('Update user');
$button = $this->button; //TEST
$this->form->button = $button; //TEST
echo $this->form;
?>
// edit.phtml - end
And the form
//
...
$this->addElement('submit', 'registerbtn', array(
'ignore' => true,
'label' => $button, //TEST
'decorators' => $this->buttonDecorators,
));
...
I fear that this is totally wrong but I don't know how to do it right.
Try something like
if ($cas1)
$form->getElement('submit')->setLabel('cas1');
else
$form->getElement('submit')->setLabel('cas2');

Categories