My parameter is an array:
Controller:
$data=......;
$this->load->view('a/p/l',$data);
The data vector has like parameter:
0 =>
array (size=4)
'email' => string '' (length=21)
...
1 =>
array (size=4)
'email' => string '' (length=21)
...
2 =>
array (size=4)
'email' => string '' (length=21)
Anyone can show mem some View that I can read the elements in to the array?
Here is a simple example
Here is my controller named welcome.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$data['default'] = array(
array(
'email' => 'sample#gmail.com',
'username' => 'username1'
),
array(
'email' => 'sample#yahoo.com',
'username' => 'username2'
),
array(
'email' => 'sample#hot.com',
'username' => 'username3'
)
);
$data['title'] = 'Sample';
$this->load->view('welcome_message', $data);
}
}
In order to call the pass $data array in the views, we make sure that we have a reference key for the array like
$data['default'] = array
$data['title'] = 'Sample';
In order for me to access those data in my view
here is a sample view named
welcome_message.php
<html lang="en">
<head>
</head>
<body>
<div id="container">
<?php
foreach ($default as $key => $value) {
?>
<h1><?php echo $value['email'];?></h1>
<?php
}
?>
<h6><?php echo $title;?></h6>
</div>
</body>
</html>
To be able to access those data pass, I used the reference key of the pass array
default and title
and from there I can do the processing already
hope It could help you out.
Hi the data array's index must be an associative index it must be letters first. CI convert the array as variable in view.
Example:
$data=array('value1'=>12,'value2'=>23)
$this->load->view('a/p/l',$data);
you can now access the values of the passed array by treating the indexes as new variable.
in your view you can get the value of value1 index like this
echo $value1;
I think it won't work if you use a number as index, it is a basic php rules in variables.
Related
First my master.blade file include menu bar using this
Include Blade file menu.blade.php
#include('menu')
But Finally I realize to send some data from db to menubar, then I create controller, Controller name is MenuController, then I create route "admin-menu". Now I want to include that link to my master blade. how to do that thank you,
To pass data to a view from either a route closure or a controller you do one of the following:
$now = \Carbon\Carbon::now();
View::make('my-view', ['name' => 'Alex', 'date' => $now]); // pass data into View:::make()
View::make('my-view')->with(['name' => 'Alex', 'date' => $now]); // pass data into View#with()
View::make('my-view')->withName('Alex')->withDate($now); // use fluent View#with()
So you'd just use them in the View::make() call as you presumably already are:
// in a route closure
Route::get('some-route', function () {
return View::make('menu', ['name' => 'Alex']);
});
// in a controller
public function someRoute()
{
return View::make('menu', ['name' => 'Alex']);
}
Interestingly, in a lot of frameworks/templating systems, if you wanted to include a partial, you'd pass the data you want to be available in that partial in the partial call, but Laravel doesn't quite do this. For example in a made-up system you may have something like this:
// in controller:
$this->render('home', ['name' => 'Alex', 'age' => 30]);
// home.php
<?php echo $name; ?>
<?php echo $this->partial('home-age', ['age' => $age]); ?>
// home-age.php
<?php echo $age; ?>
But in Laravel, all current view variables are automatically included into partials for you. Now I tend to like to specify the variables anyway (Blade does allow you to do this as above), and obviously it can be used to override a view variable:
// route:
return View::make('home', ['name' => 'Alex', 'age' => 30, 'gender' => 'male']);
// home.blade.php
{{ $name }}
#include('home-extra', ['age' => 20])
// home-extra.blade.php
{{ $age }}
{{ $gender }}
The above code would output:
Alex
20
male
So the age is overridden in the #include, but the un-overridden gender is just passed along. Hopefully that makes sense.
i have this code in codeigniter (section of form in codeigniter controller) :
$this->data['SalaryType'] = array(
'name' => 'SalaryType',
'id' => 'SalaryType',
'type' => 'text',
'value' => $this->form_validation->set_value('SalaryType'),
);
$this->data['DefaultSalary'] = array(
'name' => 'DefaultSalary',
'id' => 'DefaultSalary',
'type' => 'text',
'value' => $this->form_validation->set_value('DefaultSalary'),
);
$this->data['Salary_options'] = array(
'language' => 'monthly',
'world' => 'world'
);
(section of form in codeigniter view) :
<p>
Salary Type: <br />
<?php echo form_dropdown($SalaryType,$Salary_options,'monthly');?>
</p>
<p>
Default Salary: <br />
<?php echo form_input($DefaultSalary);?>
</p>
and i want use dropdown value but form send input value alone , and i can't access to dropdown value.
i check with print_r($_POST); but in post array observation 'DefaultSalary'.
You have initialized dropdown in wrong way
<?php echo form_dropdown($SalaryType,$Salary_options,'monthly');?>
use instead
<?php echo form_dropdown('DefaultSalary',$Salary_options,'language');?>
1st parameter is the name of the control
2nd parameter is the options array ->which is correct
3rd parameter is the selected index from the options array not value that can be in your case 'language' instead of 'monthly'
read form_helper
And you will be able to access it using $this->input->post('DefaultSalary'); and it will return the value of the option selected
May be your name attr of the drop down is not setting...
For adding id to form_drop down you can try this..
form_dropdown('country', $options_array, '1','id="select_id"')
Note : this is not tested.
Normally, the CakePHP's validation messages from models like:
class User extends AppModel {
public $name = 'User';
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
),
'regexp' => array(
'rule' => '/^[a-z0-9]{3,10}$/i',
'message' => 'Only letters and integers, min 3, max. 10 characters'
)
)
)
}
Are printed below the inputs, I mean that messages: 'message' => 'A username is required'
So it looks like:
|INPUT|
[Message]
How do I can change that so the messages gonna be added to the array:
$errors[] = 'Message';
And then, I would like to use foreach to print them in one place.
Is that possible?
CakePHP has all of the validation errors available to the view in $this->validationErrors. So I loop through them thusly:
<?php if ( !empty($this->validationErrors['Model']) ) { ?>
<div id="errorlist">
<h3>You have errors in your submission. <?php echo $warnimage; ?></h3>
<div>
<ul>
<?php foreach( $this->validationErrors['Model'] as $val ){ ?>
<li><?php echo $val; ?></li>
<?php } ?>
</ul>
</div>
</div>
<?php } ?>
EDIT
Where to place this code?
Place the code in the view where you would like it displayed.
How to disable displaying those errors below inputs?
I don't disable that display but suppose if you wished you could just unset $this->validationErrors['Model']. (untested)
Another solution is to use elements as shown in this article by Miles Johnson.
let's say I have a blog with a module "post".
now I display a post like this: post/index?id=1
in the index-action i generate a new CommentForm and pass it as $this->form to the template and it is being displayed at the bottom of a post (it's just a textfield, nothing special). form action is set to "post/addcomment". How can I display the validation errors in this form? using setTemplate('index') doesn't work because I would have to pass the id=1 to it...
thanks
UPDATE:
here's a sample code:
public function executeIndex(sfWebRequest $request)
{
$post = Doctrine::getTable('Posts')->find($request->getParameter('id'));
$this->post = $post->getContent();
$comments = $post->getComment();
if ($comments->count() > 0)
$this->comments = $comments;
$this->form = new CommentForm();
$this->form->setDefault('pid', $post->getPrimaryKey());
}
public function executeAddComment(sfWebRequest $request) {
$this->form = new CommentForm();
if ($request->isMethod('post') && $request->hasParameter('comment')) {
$this->form->bind($request->getParameter('comment'));
if ($this->form->isValid()) {
$comment = new Comment();
$comment->setPostId($this->form->getValue('pid'));
$comment->setComment($this->form->getValue('comment'));
$comment->save();
$this->redirect('show/index?id='.$comment->getPostId());
}
}
}
and my Comment Form:
class CommentForm extends BaseForm {
public function configure() {
$this->setWidgets(array(
'comment' => new sfWidgetFormTextarea(),
'pid' => new sfWidgetFormInputHidden()
));
$this->widgetSchema->setNameFormat('comment[%s]');
$this->setValidators(array(
'comment' => new sfValidatorString(
array(
'required' => true,
'min_length' => 5
),
array(
'required' => 'The comment field is required.',
'min_length' => 'The message "%value%" is too short. It must be of %min_length% characters at least.'
)),
'pid' => new sfValidatorNumber(
array(
'required' => true,
'min' => 1,
'max' => 4294967295
),
array(
'required' => 'Some fields are missing.'
))
));
}
}
and finally, indexSuccess:
<?php echo $post; ?>
//show comments (skipped)
<h3>Add a comment</h3>
<form action="<?php echo url_for('show/addComment') ?>" method="POST">
<table>
<?php echo $form ?>
<tr>
<td colspan="2">
<input type="submit" />
</td>
</tr>
</table>
</form>
that's it.
If you're using sf 1.4 just put executeAddComments and executeIndex together in one function (executeIndex for example) and you'll be fine. setTemplate won't work here.
Are you using the handleError method in the action ? The id=1 part of your url should not change if inside the handleError method, you do a return sfView::SUCCESS;
UPDATE:
It actually changes, what you need to do is submit the id along with the comment [Which I'm sure you're already doing because a comment that doesn't refer to a post doesn't make much sense], then in your handleError method, instantiate the post object there.
Try to change your form action to
<?php echo url_for('show/addComment?id=' . $post->getId()) ?>
Doing this, your post id parameter should be available even on your post request, and it should work with setTemplate('index') or forward at the end of executeAddComment
I'm trying to perform validation in the login page for the name,email and password fields. If the input fails validation,the error message should be displayed.
But here,when I fill in the details and submit, it is redirected to the next page. Only the value is not saved in the database.
Why is the message not displayed?
This is my model:
class User extends AppModel {
var $name = 'User';
var $validate = array(
'name' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Mimimum 8 characters long'
),
'email_id' => 'email'
);
function loginUser($data) {
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
$login = $this->find('all');
foreach ($login as $form):
if ($this->data['User']['email_id'] == $form['User']['email_id'] && $this->data['User']['password'] == $form['User']['password']) {
$this->data['User']['id'] = $this->find('all',
array(
'fields' => array('User.id'),
'conditions' => array(
'User.email_id' => $this->data['User']['email_id'],
'User.password'=>$this->data['User']['password']
)
)
);
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
endforeach;
}
function registerUser($data) {
if (!empty($data)) {
$this->data['User']['name'] = $data['User']['name'];
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
if($this->save($this->data)) {
$this->data['User']['id']= $this->find('all', array(
'fields' => array('User.id'),
'order' => 'User.id DESC'
));
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
}
}
}
This is my controller:
class UsersController extends AppController {
var $name = 'Users';
var $uses=array('Form','User','Attribute','Result');
var $helpers=array('Html','Ajax','Javascript','Form');
function login() {
$userId = $this->User->loginUser($this->data);
if($userId>0) {
$this->Session->setFlash('Login Successful.');
$this->redirect('/forms/homepage/'.$userId);
break;
} else {
$this->flash('Login Unsuccessful.','/forms');
}
}
function register() {
$userId=$this->User->registerUser($this->data);
$this->Session->setFlash('You have been registered.');
$this->redirect('/forms/homepage/'.$userId);
}
}
EDIT
Why is the message,example,"Minimum 8 characters long", is not being displayed when give less than 8 characters in the password field?
<!--My view file File: /app/views/forms/index.ctp -->
<?php
echo $javascript->link('prototype.js');
echo $javascript->link('scriptaculous.js');
echo $html->css('main.css');
?>
<div id="appTitle">
<h2> formBuildr </h2>
</div>
<div id="register">
<h3>Register</h3>
<?php
echo $form->create('User',array('action'=>'register'));
echo $form->input('User.name');
echo $form->error('User.name','Name not found');
echo $form->input('User.email_id');
echo $form->error('User.email_id','Email does not match');
echo $form->input('User.password');
echo $form->end('Register');
?>
</div>
<div id="login">
<h3>Login</h3>
<?php
echo $form->create('User',array('action'=>'login'));
echo $form->input('User.email_id');
echo $form->input('User.password');
echo $form->end('Login');
?>
</div>
Your validation seems correct
How about trying the following:
Make sure set your $form->create to the appropriate function
Make sure there is no $this->Model->read() before issuing Model->save();
Edit
Did you have the following?:
function register()
{
//do not put any $this->User->read or find() here or before saving pls.
if ($this->User->save($this->data))
{
//...
}
}
Edit2
IF you're doing a read() or find() before saving the Model then that will reset the fields. You should be passing the variable as type=hidden in the form. I hope i am making sense.
Edit3
I think you need to move your registerUser() into your controller because having that function in the model doesn't provide you a false return. it's always going to be true even if it has validation errors.
Comment out the redirect line and set the debug to 2 in config/core.php. Then look at the sql that is being generated to see if your insert is working. If the errors are not being displayed, maybe in the view, you are using $form->text or $form->select instead of the $form->input functions. Only the $form->input functions will automatically display the error messages.