Hi i tried to used pagination without dataProvider. Can I used this like:
public function actionShowtest($id){
$model = $this->findModel($id);
$messages= \common\models\PrMessage::find()->where(['Rel_Dialog'=>$id])->all();
$count = count($messages);
$pagination = new Pagination(['totalCount' => $count, 'pageSize'=>10]);
return $this->render('messages', [
'model' => $model,
'messages'=>$messages,
'pagination'=>$pagination
]);
}
And in my view:
<?php echo \yii\widgets\LinkPager::widget([
'pagination' => $pagination,
]); ?>
My $count return me :
int 12
and in my view i can see pagination with 1,2 but it not work becosue it show me all 12 records but I want to see this 10 records. I have 2 buttons of page but it still show me all records. What can I do to fix that?
my view:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
use yii\widgets\ListView;
/* #var $this yii\web\View */
/* #var $model common\models\BlogPost */
$this->title = $model->Id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Konwersacje'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="blog-post-view">
<?php foreach($model->prMessages as $msg): ?>
<?=$msg->relSender->Name.' '.$msg->relSender->Surname; ?>
<?=$msg->CreatedAt; ?>
<?=$msg->Text; ?>
<?php endforeach; ?>
</div>
<?php echo \yii\widgets\LinkPager::widget([
'pagination' => $pagination,
]); ?>
Its becoz Your $messages variable contains all values , its not being limited according to your pagination
Try This
public function actionShowtest($id){
$model = $this->findModel($id);
$messagesQuery = \common\models\PrMessage::find()->where(['Rel_Dialog'=>$id]);
$pagination = new Pagination(['totalCount' => $messagesQuery->count(), 'pageSize'=>10]);
$messages = $messagesQuery->offset($messagesQuery->offset)
->limit($pagination->limit)
->all();
return $this->render('messages', [
'model' => $model,
'messages'=>$messages,
'pagination'=>$pagination
]);
}
Related
I've got a form in Codeigniter 4 and I'm using the form helpers to build the form.
When I use a form_input I can reload the submitted values of the form using the old() method. Like below.
<span class="input-group-text" id="inputGroup-sizing-sm">Membership Number</span>
<?php
$current_membership_options = [
'id' => "membership_number",
'name' => "membership_number",
'class' => "form-control",
'type' => 'text'
];
echo form_input($current_membership_options, old('membership_number'))
?>
I've tried a couple of different options but I can't get it to repopulate with a form_dropdown.
THE VIEW
<span class="input-group-text" id="inputGroup-sizing-sm">Membership Type</span>
<?php
$membership_type_option = [
'id' => 'membership_type',
'name=' => 'membership_type',
'class' => 'form-select ',
'type' => 'text'
];
echo form_dropdown($membership_type_option, $membership_type, old('membership_type'));
?>
I get $membership_type from the user controller.
public function new(): string
{
$user = new User;
$data = $this->model->getMemberships();
return view('Admin/Users/new', [
'user' => $user,
'membership_type' => $data
]);
}
And the model
/**
* #throws Exception
*/
public function getMemberships(): array
{
$result = $this->db->query('select * from membership_type')->getResultArray();
$dropdown = array();
$dropdown['0'] = 'Please Select';
foreach ($result as $r)
{
$dropdown[$r['id']] = $r['type'];
}
return $dropdown;
}
Thanks in advance.
i want to add profile avatar in frontend/web/site/signup but there is an error
it said
Unknown Method – yii\base\UnknownMethodException
Calling unknown method: frontend\models\SignupForm::save()
this is the signup.php on frontend/views/site/signup.php
<?php
/* #var $this yii\web\View */
/* #var $form yii\bootstrap\ActiveForm */
/* #var $model \frontend\models\SignupForm */
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
$this->title = 'Signup';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-signup">
<h1><?= Html::encode($this->title) ?></h1>
<p>Please fill out the following fields to signup:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'form-signup'],['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'first_name')->textInput(['placeholder' => "First Name"]) ?>
<?= $form->field($model, 'last_name')->textInput(['placeholder' => "Last Name"]) ?>
<?= $form->field($model, 'username')->textInput(['placeholder' => "Username"]) ?>
<?= $form->field($model, 'email')->textInput(['placeholder' => "Email"]) ?>
<?= $form->field($model, 'password')->passwordInput(['placeholder' => "Password"]) ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
this is the SiteController.php
<?php namespace frontend\controllers;
use Yii; use yii\base\InvalidParamException; use yii\web\BadRequestHttpException; use yii\web\Controller; use yii\web\UploadedFile; use yii\filters\VerbFilter; use yii\filters\AccessControl; use common\models\LoginForm; use frontend\models\PasswordResetRequestForm; use frontend\models\ResetPasswordForm; use frontend\models\SignupForm; use frontend\models\ContactForm;
/** * Site controller */ class SiteController extends Controller {
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* #return mixed
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Logs in a user.
*
* #return mixed
*/
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
/**
* Logs out the current user.
*
* #return mixed
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* #return mixed
*/
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending your message.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
/**
* Displays about page.
*
* #return mixed
*/
public function actionAbout()
{
return $this->render('about');
}
/**
* Signs user up.
*
* #return mixed
*/
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
//upload file
$path = Yii::getAlias('#frontend') .'/web/upload/';
$imageName = $model->username;
$model->file = UploadedFile::getInstance($model,'file');
$model->file->saveAs( 'uploads/img/user'.$imageName.'.'.$model->file->extension );
$model->file->saveAs( $path.$imageName.'.'.$model->file->extension );
//save in database
$model->avatar = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save();
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}else{
return $this->render('signup', [
'model' => $model,
]);
}
}
/**
* Requests password reset.
*
* #return mixed
*/
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
/**
* Resets password.
*
* #param string $token
* #return mixed
* #throws BadRequestHttpException
*/
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->session->setFlash('success', 'New password saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
} }
<?php
namespace frontend\controllers;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\UploadedFile;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
/**
* Site controller
*/
class SiteController extends Controller
and this is the SignupForm.php on frontend/models/SignupForm.php
<?php
namespace frontend\models;
use yii\base\Model;
use common\models\User;
/**
* Signup form
*/
class SignupForm extends Model
{
public $first_name;
public $last_name;
public $username;
public $email;
public $password;
public $avatar;
public $file;
/**
* #inheritdoc
*/
public function rules()
{
return [
['first_name', 'required'],
['last_name', 'required'],
[['file'],'file', 'extensions'=>'jpg, gif, png'],
['username', 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min' => 6],
];
}
/**
* Signs user up.
*
* #return User|null the saved model or null if saving fails
*/
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->first_name = $this->first_name;
$user->first_name = $this->first_name;
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->avatar = $this->file;
return $user->save() ? $user : null;
}
}
In your controller SiteController, in action actionSignup() youre using:
$model->save()
Your model doesn't extends ActiveRecord class, so it don't have method save().
Remove this $model->save() from controller, youre saving user anyway in method signup().
I test on my localhost is working well and now show any error but after upload to the godaddy server. it is codeigniter version 2.2.6.
this error show in the login page.
Error Message 1
Message: Cannot modify header information - headers already sent by (output started at /home/user/public_html/ngapali/test/application/controllers/admin/user.php:1)
Filename: libraries/Session.php
Line Number: 433
Error Message 2
Message: Cannot modify header information - headers already sent by (output started at /home/user/public_html/ngapali/test/application/controllers/admin/user.php:1)
Filename: libraries/Session.php
Line Number: 689
Admin Controller of My Controller
<?php
class Admin_Controller extends MY_Controller{
function __construct(){
parent::__construct();
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->library('session');
$this->load->model('user_m');
$this->load->model('roomtype_m');
$this->load->model('room_m');
$this->load->model('roomcapacity_m');
//login check
$exception_uris = array(
'admin/user/login',
'admin/user/logout'
);
if(in_array(uri_string(), $exception_uris) == FALSE) {
if($this->user_m->loggedin() == FALSE) {
redirect('admin/user/login');
}
}
}}?>
My login page /user/login
Controller
<?php
class User extends Admin_Controller {
function __construct(){
parent::__construct();
}
public function index() {
$this->data['users'] = $this->user_m->get();
$this->data['subview'] = 'admin/user/index';
$this->load->view('admin/_layout_main',$this->data);
}
public function login() {
$dashboard = 'l0gadmin/dashboard';
$this->user_m->loggedin() == FALSE || redirect($dashboard);
$rules = $this->user_m->rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run() == TRUE){
if($this->user_m->login() == TRUE){
redirect($dashboard);
}else{
$this->session->set_flashdata('error','That email/password combination does not exist ');
redirect('admin/user/login','refresh');
}
}
$this->data['subview'] = 'admin/user/login';
$this->load->view('admin/_layout_modal',$this->data);
}
public function logout(){
$this->user_m->logout();
redirect('admin/user/login');
}}?>
Model
<?php
class User_m extends MY_Model {
function __construct(){
parent::__construct();
}
public function login(){
$user = $this->get_by(array(
'email'=> $this->input->post('email'),
'password' => $this->hash($this->input->post('password')),
),TRUE);
if(count($user)){
$data = array(
'name'=> $user->name,
'email' => $user->email,
'id'=> $user->id,
'loggedin'=>TRUE,
);
$this->session->set_userdata($data);
}
}
public function logout(){
$this->session->sess_destroy();
}
public function loggedin(){
return (bool) $this->session->userdata('loggedin');
}
public function hash($string){
return hash('sha512', $string . config_item('encryption_key'));
}}?>
View Page of login
<div class="row">
<div class="col-md-3">
<h2>Admin Login</h2>
<?php
echo validation_errors();
echo form_open('');
$email = array(
'name' => 'email',
'class' => 'form-control',
'placeholder' => 'Email Address'
);
echo form_input($email) . "<br/>";
$password = array(
'name' => 'password',
'class' => 'form-control',
'placeholder' => 'Password'
);
echo form_password($password) . "<br/>";
$submit = array(
'name' => 'submit',
'class' => 'form-control btn btn-primary',
'value' => 'Login'
);
echo form_submit($submit);
echo form_close();
?>
</div>
</div>
i search this problem can be of open and closed tag. I try to add all the page but it still show error. Why?.
Read the error message:
output started at
/home/user/public_html/ngapali/test/application/controllers/admin/user.php:1
/user.php file has some blank character on line 1
check for any blank space before <?php tag.
Remove it and refresh error will be go away.
One more suggestion,
Omit ending php tags ?> in controller and model files.
Read more here : Why would one omit the close tag?
This is most probably because there occured an error or warning, which is not visible because of your current display_errors setting. I would suggest turning it on in order to fix these errors/warnings.
I m trying to add cms page to topnavigation but it display only two level i want to make it like magento default rendering menu.i have tried following code to add cms page to top navigation but if there is sub menu of parent then how can i add to that child to parent using recursion method.
public function addItemsToTopmenuItems($observer)
{
$menu = $observer->getMenu();
$tree = $menu->getTree();
$node = new Varien_Data_Tree_Node(array(
'name' => 'Categories',
'id' => 'categories',
'url' => Mage::getUrl(), // point somewhere
), 'id', $tree, $menu);
$menu->addChild($node);
// Children menu items
$collection = Mage::getModel('cms/page')->getCollection()
->addFieldToFilter('is_active',1)
->addFieldToFilter('identifier',array(array('nin'=>array('no-route','enable-cookies'))));
foreach ($collection as $category) {
$tree = $node->getTree();
$data = array(
'name' => $category->getTitle(),
'id' => 'category-node-'.$category->getId(),
'url' => Mage::getUrl($category->getIdentifier()),
);
$subNode = new Varien_Data_Tree_Node($data, 'id', $tree, $node);
$node->addChild($subNode);
}
}
I was in your situation this week, and finally I achieved the solution using tree nodes. Here is the solution:
public function addItemsToTopmenuItems($observer)
{
/** #var Varien_Data_Tree_Node */
$menu = $observer->getMenu();
/** #var Varien_Data_Tree*/
$tree = $menu->getTree();
/** #var Varien_Data_Tree_Node_Collection */
$menuCollection = $menu->getChildren();
/** #var array of Varien_Data_Tree_Node*/
$nodes = $menuCollection->getNodes();
//Get "inlcude in navigation menu" parent CMS pages
$collection = Mage::getModel('cms/page')->getCollection()
->addFieldToFilter('include_in_nav',true)
->addFieldToFilter('is_active',true)
->addFieldToFilter('parent_id', array(array('null' => true), array('eq' => 0)))
->setOrder('sort_order');
$cmsHelper=Mage::helper('cms/page');
foreach ($collection as $item) {
$node = new Varien_Data_Tree_Node(array(
'name' => $item->getData('title'),
'id' => $item->getData('identifier'),
'url' => $cmsHelper->getPageUrl($item->getData('page_id')), // point somewhere
), 'id', $tree, $menu);
$menu->addChild($node);
$parent_id = $item->getData('page_id');
$this->getAllChilds($node,$parent_id);
}
}
And getAllChilds function:
private function getAllChilds($node,$parent, $defaultNode = null){
$cmsHelper=Mage::helper('cms/page');
$pages = Mage::getModel('cms/page')
->getCollection()
->addFieldToSelect('title')
->addFieldToSelect('page_id')
->addFieldToSelect('identifier')
->addFieldToFilter('parent_id', $parent)
->addFieldToFilter('is_active', 1)
->load();
$tree = $node->getTree();
if(count($pages) > 0) {
foreach ($pages as $item){
$data = array(
'name' => $item->getData('title'),
'id' => $item->getData('identifier'),
'url' => $cmsHelper->getPageUrl($item->getData('page_id')),
);
$subNode = new Varien_Data_Tree_Node($data, 'id', $tree, $node);
$node->addChild($subNode);
$node = $this->getAllChilds($subNode,$item->getData('page_id'), $node);
}
$node = $this->getAllChilds($subNode,$item->getData('page_id'));
}
$childNode = $node;
if($defaultNode !== null)
$childNode = $defaultNode;
return $childNode;
}
But you need some extra data in cms tables, like as 'parent_id' field. This is my mysql4-install-0.1.0.php file:
<?php
$installer = $this;
$installer->startSetup();
$table = $installer->getTable('cms/page');
$installer->getConnection()->addColumn($table,'parent_id',array(
'type' =>Varien_Db_Ddl_Table::TYPE_INTEGER,
'comment' => 'Parent CMS Page'
));
$installer->getConnection()->addColumn($table,'include_in_nav',
array(
'type' =>Varien_Db_Ddl_Table::TYPE_BOOLEAN,
'comment' => 'Include in navigation menu'
));
$installer->getConnection()->addColumn($table,'position',
array(
'type' =>Varien_Db_Ddl_Table::TYPE_INTEGER,
'comment' => 'Position from navigation (category) menu. 1=left; 2=right'
)); //1: left; 2: right
$installer->endSetup();
And finally you need to add these fields to the CMS / Pages backend menu: https://www.atwix.com/magento/adding-custom-attribute-to-a-cms-page/
Best regards!
Diving into this new yii 2 and Im already stuck. Im trying update a user record with a form. The original record is loading in the form, but changing the values in the form is not updating the record.
public function actionUserprofile()
{
$id = Yii::$app->user->identity->id;
$model = User::find()->where(['id' => $id])->one();
if($model->load(Yii::$app->request->post()) && $model->save())
{
Yii::$app->session->setFlash('success','You have updated your profile.');
}
return $this->render('userProfile', [
'model' => $model,
]);
}
//view form
<div>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'first_name')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'last_name')->textInput(['maxlength' => 255]) ?>
<div class="form-group">
<?= Html::submitButton('Submit',['class'=>'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
If you use User model like this https://github.com/yiisoft/yii2-app-advanced/blob/master/common/models/User.php
You may create class Profile like that:
<?php
namespace frontend\models;
use common\models\User;
use yii\base\Model;
use Yii;
/**
* Signup form
*/
class Profile extends Model
{
public $username;
public $first_name;
public $last_name;
/**
* #inheritdoc
*/
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
[['first_name', 'last_name'], 'filter', 'filter' => 'trim'],
[['first_name', 'last_name'], 'required'],
[['first_name', 'last_name'], 'string', 'max' => 255],
];
}
/**
* Signs user up.
*
* #return User|null the saved model or null if saving fails
*/
public function profileSave()
{
if ($this->validate()) {
$user = User::findOne(Yii::$app->user->id);
$user->username = $this->username;
$user->first_name = $this->first_name;
$user->last_name = $this->last_name;
if ($user->save()) {
return $user;
}
}
return null;
}
}
And change in controller
$model = User::find()->where(['id' => $id])->one();
if($model->load(Yii::$app->request->post()) && $model->save())
to
$model = new Profile();
if($model->load(Yii::$app->request->post()) && $model->profileSave())