I'm making a language selector and followed this wiki. I can implement the widget, but when I try the dropdown it doesn't make the postback. For the controller I have the idea that the controller should be: components/Controller.php in stead of components/MyController.php. But anyways both don't work. Does anyone know what to do here? I'm missing something about the essentials of catching a postback here i think..
Controller (components/controller.php):
function init()
{
parent::init();
$app = Yii::app();
if (isset($_POST['_lang']))
{
$app->language = $_POST['_lang'];
$app->session['_lang'] = $app->language;
}
else if (isset($app->session['_lang']))
{
$app->language = $app->session['_lang'];
}
Yii::app()->session['_lang'] = 'anders';
}
widget class (components/LangBox.php):
class LangBox extends CWidget
{
public function run()
{
$currentLang = Yii::app()->language;
$this->render('langBox', array('currentLang' => $currentLang));
}
}
widget view (components/views/langBox.php)
<?php echo CHtml::form(); ?>
<div id="langdrop">
<?php echo CHtml::dropDownList('_lang', $currentLang, array(
'en_us' => 'English', 'is_is' => 'Icelandic'), array('submit' => '')); ?>
</div>
<?php echo CHtml::endForm(); ?>
I am sure your code works ok, but are you actually submitting the form? You should really have a jquery that detects when the dropdown changed and submits it to the server and refreshes the page. Everything else is sound.
I have no idea what 'submit'=>'' does.
Related
I'm trying to write some data in a DB after clicking on a save button.
During my development I was writing successfully in my DB with PHP code in my view, but the PHP code was ran when the page was loaded and not when my button was clicked.
What I did is a redirection to an address that call a function in my controller and then, that redirect to a login page.
Here is my controller's code:
<?php
namespace App\Http\Controllers;
use JavaScript;
use Illuminate\Support\Facades\DB;
class bus_confirmationController extends Controller{
public function test(){
$results = DB::select('select bus_direction from bus_line where card_uid = "0xcb009299"', array(1));
JavaScript::put([
'selectionData' => $results
]);
return view('bus_confirmation');
}
public function postRequest(){
DB::table('bus_line')->insert(
array('ID' => '', 'bus_direction' => '77t', 'card_uid' => '0xcb009299')
);
return view('home');
}
}
Here is my view's code:
[...]
<div class="panel panel-default" id="save" onclick="savedata()" >
SAVE
</div>
[...]
<script type="text/javascript">
function savedata() {
var toReturn = [];
var data = ["88t", "85t","77t","redLinet"];
for (i = 0; i < data.length; i++) {
var image = document.getElementById(data[i]).style.visibility;
if (image==="visible" || image===""){
toReturn.push([data[i], "visible"]);
}
}
window.location = 'Bus_confirmationSend';
//Where I used to do my request to write my data
/*DB::table('bus_line')->insert(
array('ID' => '', 'bus_direction' => '88t', 'card_uid' => '0xcb009299')
);*/
console.log(toReturn);
}
</script>
Here is what's inside web.php
Route::get('/bus_confirmationSend', 'bus_confirmationController#postRequest');
I know my connexion to my database is working as the function 'test' from the controller works, I can retrieve data from my DB. I also know that my first redirection to 'bus_directionController' works as the second redirection to 'home' works.
Am I missing something? I really don't understand what can be wrong here.
It may be because you have window.location = 'Bus_confirmationSend'; but your route starts with lower case b
I'm really new to Yii and as a starter, I want to know how to get the value from the textbox when the button is pressed.
<?php CHtml::textField($name,$value,array('submit'=>'')); ?>
<?php echo CHtml::submitButton('Greet!',array(
'submit' => 'message/goodbye')); ?>
Keep your view some thing like
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'aForm',
'htmlOptions' => array('onsubmit'=>"return false;"),
));
?>
<?php echo CHtml::textField('name', 'value'); ?>
<?php echo CHtml::submitButton('Greet!', array('onclick' => 'getValue()'));?>
<?php $this->endWidget(); ?>
And the Action Script for the onclick event is
<script type="text/javascript">
function getValue()
{
$text=$("#aForm").find('input[name="name"]').val();
alert($text);
//$formData=$("#aForm").serialize();
}
</script>
UNDERSTANDING THE BASIC CONCEPT
You have to remember that Yii is an MVC framework ( Model, View Controller ) and the best practice is to keep the entire structure like so. The best way to learn it is from the awesome forum that they have.
Hence, to define a scenario where you would like to save a data/textbox from the form, you would be following the following workflow :
A BASIC WORKFLOW
Assuming that you don't want to save the data in the Database. :
I would be assuming that a basic knowledge of the how the framework works is known. You can check out the guide and the other tutorials if not.
This is a basic workflow in which the data would be taken from the form and validated in the model.
Create a model file in your protected/models folder
Example : Lets name this file as FormData.php
<?php
class FormData extends CFormModel{
public $name;
public $email;
public function rules()
{
return array(
array('name , email','required'), // This rule would make it compulsory for the data to be added.
array('email','email'), // This will check if the email matches the email criteria.
);
}
public function attributeLabels()
{
return array(
'name' => 'Enter your name',
'email' => 'Enter your email',
);
}
}
?>
2. After this , in your protected/FormController.php
Add this :
<?php
class Formdata extends CController{
public function actionCoolForm()
{
$model = new FormData();
if(isset($_POST['FormData'])){
$model->attributes = $_POST['FormData'];
if($model->validate()){
// Do whatever you want to do here.
}
}
$this->render('someview',array('model'=>$model));
}
}
?>
3. Now to add the form in your page is easy :
<?php echo CHtml::form('formdata/coolform','post'); ?>
<?php
echo CHtml::activeTextField($model,'name');
echo CHtml::activeTextField($model,'email');
?>
<?php echo CHtml::endForm(); ?>
Now to add it in the database
The best and the easiest method of adding it in the database is to use the Gii.
But the code is nearly identical, except that the model extends CModel.
I hope that I was able to help.
This is a custom CMS where menu list can be edited in backend and then need to be displayed in front end layout.
Menu controller is in -/application/modules/admin/controllers
and the code for render action is :
<?php
class Admin_MenuController extends CMS_Controller_AdminbaseController
{
public function renderAction()
{
$menu = $this->_request->getParam('menu');
$mdlMenuItems = new Model_MenuItems();
$menuItems = $mdlMenuItems->getItemsByMenu($menu);
if(count($menuItems)>0){
foreach($menuItems as $item){
$label = $item->label;
if(!empty($item->link)){
$uri = $item->link;
}else{
$uri = '/page/open/id/' . $item->pageId;
}
$itemArray[] = array(
'label' => $label,
'uri' => $uri
);
}
$container = new Zend_Navigation($itemArray);
$this->view->navigation()->setContainer($container);
}
}
}
When rendered in - /application/modules/admin/views/scripts/menu/render.phtml using
<? echo $this->navigation()->menu(); ?>
it renders fine, but instead I want to render it in /application/layouts/scripts.
Any help is much appreciated.
go to Zend_View_Helper create exapmle.php as an example;
on it insert function
public function abc()
{
//insert your code here
}
then go to layout.phtml and call it
echo $this->abc();
You can render it in layout this way <?= $this->action('render', 'menu', 'admin');?>
Additionally you can pass some parametrs in array.
Hope this helps you.
I have a form set up in a controller that both loads the form and its previously populated contents from a database and processes the form as needed. The problem is $this->form_validation->run() never evaluates to FALSE, even if rules are not met.
Controller:
public function edit_version($node, $lang)
{
// load form validation class
$this->load->library('form_validation');
// set validation rules
$this->form_validation->set_rules("title|Title|required");
// run validation
if ($this->form_validation->run() !== FALSE)
{
// save input to database
die("validation successful");
}
else
{
// either validation was not passed or no data to validate
// load page edition view and display databse contents
// load page model
$this->load->model("page_model");
// get the page from database
$data["page"] = $this->page_model->get_page($node, $lang);
// load views
$this->load->view("admin/header.php", array("title" => "Edit page no.: $node, $lang version - Admin"));
$this->load->view("admin/pages/edit_page.php", $data);
$this->load->view("admin/footer.php");
}
}
Model:
class Page_model extends CI_Model
{
public function get_page($node, $lang)
{
// load the page
return $this->db->get_where("pages", array("node" => $node, "lang" => $lang))->row();
}
public function save_version($page)
{
$this->db->where("node", $page["node"]);
$this->db->where("lang", $page["lang"]);
$this->db->update("pages", $page);
}
public function search($query)
{
return $this->db->get_where("pages", $query)->result();
}
}
View:
<h2>Edit page</h2>
<?php
// load form helper
$this->load->helper("form");
// open a form
echo form_open("admin/page/{$page->node}/edit/{$page->lang}");
// print validation errors
echo validation_errors();
// title and content fields
echo form_label("Title: ", "title");
echo form_input("title", set_value("title", $page->title));
// aesthetic line break
echo "<br>";
echo form_label("Content: ", "content") . "<br>";
echo form_textarea("content", set_value("content", $page->content));
// save button and close form
echo form_submit("submit", "Save page");
echo form_close();
Thanks in advance.
syntax for setting rule is
$this->form_validation->set_rules('field_name', 'Label', 'rule1|rule2|rule3');
by considering rules your set rule line will be
$this->form_validation->set_rules('title','Title', 'required");
I'm not a CodeIgniter seasoned dev but from documentation is the proper syntax not the following?
$this->form_validation->set_rules("title","Title","required");
As per this link:
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#validationrules
Use
$this->form_validation->set_rules("title","Title","required");
instead of this
$this->form_validation->set_rules('title','Title','required');
I have tested this. It works like a Charm.
We have a actionSearchType in our User Controller as follows:
public function actionSearchType()
{
if (Yii::app()->user->isGuest == true)
$this->render('login');
else
$this->render('search_type');
}
Our actionLogin in our User Controller is as follows:
public function actionLogin()
{
$model= new Users();
// if it is ajax validation request
if(isset($_POST['ajax']))
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
$this->redirect(Yii::app()->user->returnUrl);
}
}
// display the login form
$this->render('login',array('model'=>$model));
}
The goal is to ensure that only authenticated users can execute the options on the search type view. When I run this page, I receive an error stating Undefined variable: model.
A snippet of the login view is as follows:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username'); ?>
<?php echo $form->error($model,'username'); ?>
</div>
What steps must be taken to remedy the above error and properly check to ensure we have an authenticated user?
update
I changed actionSearchType to render the Login Widget per below:
public function actionSearchType()
{
if (Yii::app()->user->isGuest)
$this->widget('ext.LoginWidget');
else
$this->render('search_type');
}
This indeed resolved the error initially seen. A new problem is that there's no styling of the login widget when it renders. Should I echo my tags with appropriate stylesheet classes, or is there a bit more elegant way of doing that?
public function actionSearchType() {
if (Yii::app()->user->isGuest)
$this->redirect('/user/login');
$this->render('search_type');
}
Notes:
to do something when user is guest, simply use if(Yii::app()->user->isGuest) { statement }
to do something when user is logged in, simply use if(!Yii::app()->user->isGuest) { statement }
in the second code, public function actionLogin(), I think you have 2 more closing curly brackets than needed. Anyway, the login action should look like this:
public function actionLogin() {
$formModel = new Login_Form; // Login_Form.php should be in models folder
if (isset($_POST['Login_Form'])) {
$formModel->attributes = $_POST['Login_Form'];
if ($formModel->validate() && $formModel->login()) {
$this->redirect('/'); // replace / with stuff like Yii::app()->user->returnUrl
}
}
$this->render('login', array(
'formModel'=>$formModel,
));
}
Instead of rendering the view redirect to the user login page / action so you don't have to recreate it.
$this->redirect('login');
Somewhere in search_type you are referencing the variable $model which you do not hand over to the render() function. You need to define that variable otherwise the view will create an Exception.
I don't know which Model/Class your search_type view is expecting but you will need to initialize it before you hand it over to the view like this:
$this->render('search_type',array(
'model' => $model,
));
Here a good read about this topic: Understanding the view rendering flow