I use basic mode on Yii2 framework. I create two controllers - SiteController and CategoryController. I have two folders with few views - site (index and about) and category (category and search).
When i render view by SiteController evething is ok, but when i render view by CategoryController actionSearch - do not call main.php and do not show any html in view, but if i call die - the results is there.
Here is a code:
model:
namespace app\models;
use yii\db\ActiveRecord;
class Categories extends ActiveRecord
{
public static function tableName()
{
return 'categories';
}
public function getProducts(){
return $this->hasMany(Products::className(), ['category_id' => 'id']);
}
}
and CategoryController:
public function actionSrch() {
$cat = Categories::findOne(1);
$q = Yii::$app->request->get('q');
if(isset($q) and $q!=''){
$query = Products::find()->where(['like', 'title', $q]);
// pagination
$pages = new Pagination([
'totalCount' => $query->count(),
'pageSize' => 4,
'forcePageParam' => false,
'pageSizeParam' => false ]);
$products = $query->offset($pages->offset)->limit($pages->limit)->all();
}else{
$products = Products::find()->where('title<>:title', [':title'=>''])->all();
}
$this->render('search', compact('products','pages', 'q', 'cat'));
}
and the Search form:
<div class="col-sm-3">
<div class="search_box pull-right">
<form action="<?= \yii\helpers\Url::to(['categories/search']) ?>" method="get">
<input type="text" placeholder="Search" name="aaa">
</form>
</div>
</div>
and the view in search.php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\LinkPager;
<ul class="catalog category-products">
<?= \app\components\MenuWidget::Widget(['tpl' => 'menu']) ?>
</ul>
<div class="col-sm-9 padding-right">
<div class="features_items"><!--features_items-->
<?php if(!empty($products)): ?>
<?php $i = 0; foreach($products as $prd): ?>
<h2><?= $prd->price ?></h2>
<?php endif; ?>
<?php endforeach; ?>
<?php else :?>
<div class="alert alert-danger">Do not have products!!!</div>
<?php endif; ?>
First chack your action name actionSrch or actionSearch.
And add return before render file like below.
public function actionSrch() {
$cat = Categories::findOne(1);
$q = Yii::$app->request->get('q');
if(isset($q) and $q!=''){
$query = Products::find()->where(['like', 'title', $q]);
// pagination
$pages = new Pagination([
'totalCount' => $query->count(),
'pageSize' => 4,
'forcePageParam' => false,
'pageSizeParam' => false
]);
$products = $query->offset($pages->offset)->limit($pages->limit)->all();
}else{
$products = Products::find()->where('title<>:title', [':title'=>''])->all();
}
return $this->render('search', compact('products','pages', 'q', 'cat'));
}
Refere Yii2 Base Actions and Yii2 Render()
Related
I created a method in a model of CI4 to query a search results. I need to paginate search results but the URL not provide results. I need to standard way for pagination in CI4.
Here is model method -
<?php
public function search($key)
{
$builder = $this->table('apps_common_all');
$builder->Like('name',$key,'after');
$query = $builder->paginate(51);
return $query;
}
?>
controller method is -
<?php
public function result()
{
$key = $this->request->getVar('s');
$apps = new AppsModel();
$data = [
'items' => $apps->search($key),
'pager' => $apps->pager,
];
return view('search/index',$data);
}
?>
Pagination code in view page
<?php if ($pager) :?>
<?php $pagi_path=getenv('pagi_path').'search_result'; ?>
<?php $pager->setPath($pagi_path); ?>
<?= $pager->links() ?>
<?php endif ?>
when pagination link clicked the url not provide results
http://myshahadat.com/demo/apkdownload/search_result?s=a&page=2
and my route is
<?php $routes->get('/search_result', 'Search::result'); ?>
I am coding a form to get user input and then pass that information to a controller and execute a function based on that, at this point I can not pass the data to the controller using POST method, I get empty vars.
So the Controller function display the view form correctly, I can type on the textboxes, after press submit button I get a setFlash custom message that the parameters are empty. I am using a model class with just two parameters.
a) This is the model:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
class SendmailForm extends Model
{
public $template;
public $emtransport;
/**
* #return array the validation rules.
*/
public function rules()
{
return [
[['template', 'emtransport'], 'required'],
];
}
}
b) This is the view:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;
$this->title = 'Send Mail';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-contact">
<h1><?= Html::encode($this->title) ?></h1>
<?php if (Yii::$app->session->hasFlash('sminfo')): ?>
<div class="alert alert-success">
<?= Yii::$app->session->getFlash('sminfo');?>
</div>
<?php else: ?>
<p>
SendMail Exercise. Please choose needed options bellow:
</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'sendmail-form']); ?>
<?= $form->field($model, 'template')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'emtransport') ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'value'=>'one', 'name'=>'sendbtn']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
<?php endif; ?>
</div>
And this is the controller's function:
public function actionSendmail(){
$model = new SendmailForm();
if ($model->load(Yii::$app->request->post())) {
$template = Yii::$app->request->post('template');
$emailTransport = Yii::$app->request->post("emtransport");
if($emailTransport=="local"){
for($i=0;$i<=2;$i++){
$xclient = 'client' . $i;
\app\models\User::findByUsername($xclient)->sendMail($template, 'Welcome To XYZ Services', ['accountInfo' => 'www.mysite.com']);
}//end of for loop
Yii::$app->session->setFlash("sminfo", "Emails sent successfully to the Clients");
return $this->refresh();
}//end of second if loop
else{
Yii::$app->session->setFlash("sminfo", "Params could not be verified!. Contact Tech Support");
return $this->refresh();
}
}//end of post if loop
return $this->render('sendmail', [
'model' => $model,
]);
}
The idea is to get the values from the view, at this moment I am getting empty values-
Two parts below:
$template = Yii::$app->request->post('template');
$emailTransport = Yii::$app->request->post("emtransport");
Change the following:
$template = $model->template;
$emailTransport = $model->emtransport;
After editing
public function actionSendmail(){
$model = new SendmailForm();
if ($model->load(Yii::$app->request->post())) {
$template = $model->template;
$emailTransport = $model->emtransport;
if($emailTransport=="local"){
for($i=0;$i<=2;$i++){
$xclient = 'client' . $i;
\app\models\User::findByUsername($xclient)->sendMail($template, 'Welcome To XYZ Services', ['accountInfo' => 'www.mysite.com']);
}//end of for loop
Yii::$app->session->setFlash("sminfo", "Emails sent successfully to the Clients");
return $this->refresh();
}//end of second if loop
else{
Yii::$app->session->setFlash("sminfo", "Params could not be verified!. Contact Tech Support");
return $this->refresh();
}
}//end of post if loop
return $this->render('sendmail', [
'model' => $model,
]);
}
I did some changes to the Controller and now it works, those are them:
//at the beginning of the Controller:
use app\models\SendmailForm;
//two lines changed in the function:
$model->template = $_POST['SendmailForm']['template'];
$model->emtransport = $_POST['SendmailForm']['emtransport'];
That's all I needed. Best regards
I am trying to create dynamic menu using PHP Codeigniter.
There are some Main Menu
Each Main Menu have some Sub_Menu Like, Categories ->Hardware, Software etc.
I somehow made it but there is an issue, the Main menu is showing correctly but the sub menu under main menu is repeating in each Main menu.
This is the image of the issue:
My View Code
<ul class="slimmenu">
<?php foreach($menus as $menu): ?>
<li>
<?php echo $menu -> Menu_Name;?>
<ul>
<?php foreach($submenus as $submenu): ?>
<li>
<?php echo $submenu -> Sub_Menu_Name;?>
</li>
<?php endforeach;?>
</ul>
</li>
<?php endforeach;?>
</ul>
My Controller Code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MainSystem extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model('menusys','ms');
}
function menu()
{
$this->data['menus'] = $this->ms->get_menu();
$this->data['submenus'] = $this->ms->get_submenu();
$this->load->view('index', $this->data);
}
function add_menu()
{
$data = array(
'Menu_Name' => $this->input->post('mname'),
'Menu_Link' => $this->input->post('mlink'),
);
$this->ms->adm($data);
}
function sub_menu()
{
$this->data['mmenu'] = $this->ms->get_menu();
$this->load->view('submenu', $this->data);
}
function add_submenu()
{
$data = array(
'Main_Menu_Name' => $this->input->post('mmname'),
'Sub_Menu_Name' => $this->input->post('mname'),
'Sub_Menu_Link' => $this->input->post('mlink'),
);
$this->ms->adsm($data);
}
}
?>
My Model Code
<?php
defined('BASEPATH') or exit('no direct script directy allowed');
/**
*
*/
class menusys extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function adm($data)
{
$this->db->set('Is_Active',0);
$this->db->insert('main_menu',$data);
$this->session->set_flashdata('msg', 'Meun has been added');
redirect('MainSystem/menu');
}
//sub-menu Section
public function get_menu()
{
//$this->db->where('Is_Active',1);
// $this->db->select('*');
// $this->db->from('main_menu');
// $this->db->join('sub_menu', 'main_menu.Menu_Name = sub_menu.Main_Menu_Name','inner');
// $query = $this->db->get();
// return $query->result();
//
$query=$this->db->get_where('main_menu',array('Is_Active'=>1));
return $query->result();
}
function get_submenu()
{
$this->db->where('main_menu.Menu_Name = sub_menu.Main_Menu_Name');
$this->db->select('*');
$this->db->from('sub_menu');
$this->db->join('main_menu', 'main_menu.Menu_Name = sub_menu.Main_Menu_Name','inner');
$query = $this->db->get();
return $query->result();
}
public function adsm($data)
{
$this->db->set('Is_Active',1);
$this->db->insert('sub_menu',$data);
$this->session->set_flashdata('msg', 'Meun has been added');
redirect('MainSystem/menu');
}
}
What I Want: I want that each Sub_Menu will show under his parent menu.
Any help will be appreciated.
UPDATE
This is sub-menu table image.
you need to format your menu array and loop it something like this
$menu = array(
'menu_name_1' => array(
'submenu1_1' => 'www.something.com',
'submenu1_2' => 'www.something.com',
),
'menu_name_2' => array(
'submenu2_1' => 'www.something.com',
'submenu2_2' => 'www.something.com',
)
);
foreach($menu as $menu_name => $submenu){
echo $menu_name.'<br>';
if (!empty($submenu)){
foreach($submenu as $submenu_name => $submenu_link){
echo ''.$submenu_name.'<br>';
}
}
}
You have array with menu names and submenu. First you loop menu name and check dose it has submenu, it if has, you loop submenu and make links.
I am trying to do following things...I have a page which is been used for searching as well as displaying results. I have done the following things, have a controller which is filtering data and I think its working fine till now..., but now have no idea how to display the desired result in my view page.
/*Codes for Controller */
public function actionSearch()
{
$model = new SearchEmployee();
/*Getting Data From Search Form For Processing */
if (isset($_POST['SearchEmployee'])) {
$category = $_POST['SearchEmployee']['category_id'];
$skills = $_POST['SearchEmployee']['skills'];
$experience = $_POST['SearchEmployee']['experience'];
$model = SearchEmployee::model()->find(array(
'select' => array('*'), "condition" => "category_id=$category AND key_skills like '%$skills%' AND experience=$experience",
));
$this->render('search', array('model' => $model));
}
/*Getting Data From Search Form For Processing */
$this->render('search', array('model' => $model));
}
In View: I have done like below, not posting full view, just portion of section where I have to show results.
<div class="view">
<h1>Results </h1>
<div class="view" id="id">
<h1> Records Display </h1>
<h4>Name: <?php echo $model->name; ?></h4>
<h4>Skills: <?php echo $model->experience;?></h4>
<h4>Experience: <?php echo $model->key_skills; ?></h4>
<h5> <?php echo CHtml::submitButton('VIew Details'); ?></h5>
</div>
</div>
I don't know whether I am on right track.
You should try with different word rather then model like modelData etc.
public function actionSearch()
{
$model = new SearchEmployee();
/*Getting Data From Search Form For Processing */
if (isset($_POST['SearchEmployee'])) {
$category = $_POST['SearchEmployee']['category_id'];
$skills = $_POST['SearchEmployee']['skills'];
$experience = $_POST['SearchEmployee']['experience'];
$modelData = SearchEmployee::model()->find(array(
'select' => array('*'), "condition" => "category_id=$category AND key_skills like '%$skills%' AND experience=$experience",
));
$this->render('search', array('model' => $model));
}
/*Getting Data From Search Form For Processing */
$this->render('search', array('modelData' => $modelData));
}
Issue/Question: I'm using CodeIgniter to build an event calendar, and I have included a sharing option. This option works at a base level, but only displays the users' ID (primary key) in an <ul>. This isn't ideal, and I would like to show the users' first and last names in the <ul> instead. I thought creating an associative array would work, but I'm receiving funky results. The first and last name echo out as "Array Array" when the page loads, and the URL id comes up as "Array" when you select the "Array Array" link. I'm wondering what is wrong in my logic.
Funky link generated in view:
Array Array
Funky URL that is linked to "Array Array":
http://example.com/user/shared/view/Array
Modified Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Shared extends Common_Auth_Controller {
private $end_user;
public function __construct()
{
parent::__construct();
$this->end_user = $this->ion_auth->user()->row();
$data['end_user'] = $this->end_user;
$this->load->vars($data);
$this->load->model('events_model', 'events');
}
public function index()
{
$title['title'] = 'Shared';
$this->load->model('shared_model','shared');
$data['sharers'][] = array(
'shared_owner_id' => $this->shared->get($this->end_user->id),
'owner_first_name' => $this->shared->get($this->end_user->first_name),
'owner_last_name' => $this->shared->get($this->end_user->last_name),
);
$this->load->view('public/head_view', $title);
$this->load->view('user/header_view');
$this->load->view('user/shared_view', $data);
$this->load->view('user/footer_view');
}
Modified View:
<div class="hide-on-phones">
<ul>
<?php foreach($sharers as $key => $value): ?>
<li><?php echo $value['owner_first_name']." ".$value['owner_last_name'] ?></li>
<?php endforeach; ?>
</ul>
</div>
Model:
class Shared_model extends crud_model {
public function __construct()
{
parent::__construct();
$this->pk = 'id';
$this->table_name = 'shared';
}
public function get($shared_to_user_id)
{
$this->db->where('shared_to_id', $shared_to_user_id);
$ids = parent::get_all();
$users = array();
foreach ($ids as $id)
{
$users[] = $id->owner_id;
}
return $users;
}
}
Thank you so much for your help, and let me know if there is any more information that may be required. Below are the original view and controllers that work, but are not preferable.
Original Controller:
public function index()
{
$title['title'] = 'Shared';
$this->load->model('shared_model','shared');
$data['sharers'] = $this->shared->get($this->end_user->id);
$this->load->view('user/head_view', $title);
$this->load->view('user/header_view');
$this->load->view('user/navigation_view');
$this->load->view('user/shared_view', $data);
$this->load->view('user/footer_view');
}
Original View:
<?php foreach($sharers as $s): ?>
<li><?php echo $s ?></li>
<?php endforeach; ?>
Disclaimer: I'm new to web development, and I suck at associative arrays (apparently).
Your $data['sharers'] array doesn't have arrays as $values. Therefore, the way you are calling the $value[]'s in your foreach aren't working. You have no reason for calling the foreach at this point.
<div class="hide-on-phones">
<ul>
<li><a href="<?=base_url('user/shared/view/'.$sharers['shared_pk_id'])?>">
<?=$sharers['first_name'] . ' ' . $sharers['last_name']?>
</a>
</li>
</ul>
</div>
I expect you will later on fill an array with the data, in which case you can fill it as
$data['sharers'][] = array(
'shared_pk' => $this->shared->get($this->end_user->id),
'first_name' => $this->events->get($this->end_user->first_name),
'last_name' => $this->events->get($this->end_user->last_name)
);
Which, in turn can be looped using
<div class="hide-on-phones">
<ul>
<? foreach($sharers as $sharer): ?>
<li>
<a href="<?=base_url('user/shared/view/' . $sharer['shared_pk'])?>">
<?=$sharer['first_name'] . ' ' . $sharer['last_name']?>
</a>
</li>
<? endforeach; ?>
</ul>
</div>
I've figured it out. I needed to create an associative array in my model; not my controller. Thanks to everyone for your help!
Model:
class Shares_model extends crud_model {
public function __construct()
{
parent::__construct();
$this->pk = 'id';
$this->table_name = 'shares';
}
public function get($shared_to_user_id)
{
$this->db->where('shared_to_id', $shared_to_user_id);
$ids = parent::get_all();
$users = array();
foreach ($ids as $id)
{
$users[$id->owner_id]['owner_id'] = $id->owner_id;
$users[$id->owner_id]['owner_first_name'] = $id->owner_first_name;
$users[$id->owner_id]['owner_last_name'] = $id->owner_last_name;
}
return $users;
}
}
View:
<ul>
<?php foreach($sharers as $s): ?>
<li><?php echo $s['owner_first_name']." ".$s['owner_last_name'] ?></li>
<?php endforeach; ?>
</ul>
Controller:
public function index()
{
$title['title'] = 'Shared';
$this->load->model('shares_model','shares');
$data['sharers'] = $this->shares->get($this->end_user->id);
$this->load->view('public/head_view', $title);
$this->load->view('user/header_view');
$this->load->view('user/shared_view', $data);
$this->load->view('user/footer_view');
}
If we take your $data['sharers'] array and put in values for the php, then we would get something like this:
$data['sharers'] = array(
0 => array(
'id' => 1234,
'first_name' => 'John',
'last_name' => 'Doe'
),
1 => array(
'id' => 1235,
'first_name' => 'Jane',
'last_name' => 'Doe'
)
);
So, when you loop through this in your view, you need to access these correctly:
foreach($sharers as $key => $value):
// at this point, in the first iteration of the loop
// $key is 'id', or 'first_name', or 'last_name'
// and $value is 1234, or 'John', or 'Doe'
endforeach;
So, to loop through the sharers a bit easier, you just need to update your foreach a bit. At this point, change your view to this:
<div class="hide-on-phones">
<ul>
<?php foreach($sharers as $sharer): ?>
<li>
<a href="<?php echo base_url('user/shared/view/'.$sharer['shared_pk_id']) ?>">
<?php echo $sharer['first_name']. " " .$sharer['last_name'] ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>