Phalcon does change views - php

<?php
class IndexController extends \Phalcon\Mvc\Controller {
public function indexAction(){
}
}
?>
<?php
class SignupController extends \Phalcon\Mvc\Controller {
public function indexAction(){
}
}
?>
<?php
echo "<h1>Hello!</h1>";
echo Phalcon\Tag::linkTo( "signup", "Sign Up Here!");
?>
<?php use Phalcon\Tag; ?>
<h2>Sign up using this form</h2>
<?php echo Tag::form( "signup/register" ); ?>
<p>
<label for="name">Name</label>
<?php echo Tag::textfield( "name" ); ?>
</p>
<p>
<label for="email">E-Mail</label>
<?php Tag::textfield( "email" ); ?>
</p>
<p>
<?php echo Tag::submitButton( "Register" ); ?>
</p>
</form>
I was following a tutorial on phalcon framework here but it can't get it to work. I have created the controllers for the index page and the signup page. I also created the views for the index controller and the view for the signup controller.
What happens is that when I click on the link to go to the signup page it shows the url correct which means we should be on the signup page but it shows the index view not the signup view. Basically when i click on the signup link the only thing that changes in the browser is the url but not the page.
anyone know what is going on here?

Ok,
I got this working in the end.
Make sure that (in my case Nginx) you confirm that it has been set up correctly.
The second thing to look at is the code to handle the request. I have used this:
$application = new \Phalcon\Mvc\Application();
$application->setDI($di);
if (!empty($_SERVER['REQUEST_URI'])) {
$pathInfo = $_SERVER['REQUEST_URI'];
} else {
$pathInfo = '/';
}
echo $application->handle($pathInfo)->getContent();
This isn't exactly what I wanted, but for some reason my PATH_INFO was coming out as empty, even when I have set cgi.fix_pathinfo to 1 in the php.ini
Hope this helps.

Related

controller not displaying a message in phalcon php

I’m trying to make a simple example in Phalcon PHP framework, so i have a view which contain two fields name and email and a submit button. When i click in this button a function of a controller is called to store the name and the email in the DB. This action goes well the problem is I’m trying to display a message after the action ends but i still have the view that contain the form (name, email). Here's my code.
My checkout controller.
<?php
class CheckoutController extends \Phalcon\Mvc\Controller
{
public function indexAction()
{
}
public function registerAction()
{
$email = new Emails();
//Stocker l'email et vérifier les erreurs
$success = $email->save($this->request->getPost(), array('name', 'email'));
if ($success) {
echo "Thanks for shopping with us!";
} else {
echo "Sorry:";
foreach ($user->getMessages() as $message) {
echo $message->getMessage(), "<br/>";
}
}
}
}
The view
<!DOCTYPE html>
<html>
<head>
<title>Yuzu Test</title>
</head>
<body>
<?php use Phalcon\Tag; ?>
<h2>Checkout</h2>
<?php echo Tag::form("checkout/register"); ?>
<td>
<tr>
<label for="name">Name: </label>
<?php echo Tag::textField("name") ?>
</tr>
</td>
<td>
<tr>
<label for="name">E-Mail: </label>
<?php echo Tag::textField("email") ?>
</tr>
</td>
<td>
<tr>
<?php echo Tag::submitButton("Checkout") ?>
</tr>
</td>
</form>
</body>
</html>
You can use Flash Messages, so you don't have to break the application flow.
Regards
echo() during controller code won't (shouldn't) work unless you turn off your views, because its buffered and cleared after dispatching.
If you want to be sure it's happening this way, just add die() at the end of registerAction() method.
If you create separate view for registerAction(), you can use there variables you declare with $this->view->message = ... or $this->view->setVar('message', ...) in controller method. Than, in view file you can reuse them by <?php echo $this->view->message; ?> or <? echo $message; ?>.
I think you have to write following line in the end of your controller function registerAction
$this->view->disable();

CodeIgniter view not loading and white screen displayed instead

I've been debugging this piece of code for hours now without success. All I'm trying to do is get a view to load. Instead of it loading, I get a white screen and no error messages anywhere.
Here's the code from the controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->view('welcome_message');
}
//echo "we made it to the function";
public function login_form()
{
$this->load->view('login_form');
}
public function login_submit()
{
print_r( $_POST );
$this->load->model('Usermodel', 'users');
$match = $this->users->authenticate_user( $_POST['email'], $_POST['password'] );
if( $match )
{
echo "User exists in database!";
}
else
{
echo "Email or password is wrong, bretheren!";
}
}
}
The important part is the "function login_form". Here is the code for that view:
<form action="<?php base_url() ?>welcome/login_submit" method="post">
<label>
email:
<input id="email" name="email" />
</label>
<label>
password:
<input type="password" id="password" name="password" />
</label>
<input type="submit" value="Log me in!" />
</form>
This is the link I'm using in my browser to get to the page:
localhost/intranet/index.php/welcome/login_form
The code all looks fine to me and I just can't seem to figure out where the program is breaking. Does anybody have any ideas?
EDIT: I took out the shorthand but I have the same problem.
1) You're missing an echo...
<?php echo base_url() ?>
2) To use base_url(), you also need to load the URL Helper someplace.
https://www.codeigniter.com/user_guide/helpers/url_helper.html
3) I strongly recommend reading the entire documentation, including the simple demos & tutorials, before starting a CodeIgniter project...
https://www.codeigniter.com/user_guide/
4) Although you can use PHP short-tags (as per your server config), they're not recommended.
https://www.codeigniter.com/user_guide/general/styleguide.html#short-open-tags
You have to either enable the URL Helper in your configuration, or in the controller if you want to use the base_url() function:
$this->load->helper('URL');
<form action="<?php base_url() ?>welcome/login_submit" method="post">
should be
<form action="<?php echo base_url() ?>welcome/login_submit" method="post">
OR Shorthand if you configure it properly:
<form action="<?=base_url() ?>welcome/login_submit" method="post">
Noiticed the post about not being able to use shorthand with CodeIgniter and yes you can, I've just completed a project where we used shorthand. It's just how you configure your php.ini
<?= is just short for <?php echo
you are using codeigniter so why not use it's all functionality. you can create form in codeigniter like this
So you no need to use base_url or so and it is the right method to use in codeigniter.
<?php echo form_open("welcome/login_submit",array('method'=>'post')); ?>
<label>
email:
<?php echo form_input(array('name'=>'email','id'=>'email')); ?>
</label>
<label>
password:
<?php echo form_password(array('name'=>'password','id'=>'password')); ?>
</label>
<?php
echo form_button(array('type'=>'submit','value'=>'Log me in!'));
echo form_close(); ?>

CodeIgniter session not setting

I am using sessions to make a multi-stage form, I want to record the information through each stage using codeIgniter sessions then input the session info all into the database at the end.
What I want to do is go from stage 1 in the form, enter a number into an input box, submit it, grab the input number through post and set that number from the post in the session. Then in stage 2 grab the information from the session and simply echo it, then at least I know it's working.
I had my code working earlier, but after moving it around and clearing the cache in chrome it suddenly stopped working and I can't see anything that's wrong with. Please note I'm working in chrome, but I've also tried this in firefox and ie. I am loading the session library with config/autoload and have my encryption key set in the config. I have tried closing chrome and reopening it. Any help would be most appreciated!
Controller: "scholarshiphistory.php"
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Scholarshiphistory extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('site_model');
}
//stage 1 of multipart form
public function addhist_selectstudent(){
$this->load->helper('form');
$data = $this->site_model->general();
$this->load->view('view_addhist_selectstudent',$data);
$this->load->view('view_footer',$data);
//set session info if user submits
if($this->input->post('studentSearch')){
$this->session->set_userdata('studentNationalId', $this->input->post('studentSearch'));
}
}
//stage 2 of multipart form
public function addhist_scholarshipdetails(){
if (!$this->session->userdata('studentNationalId')) {
//no session
$data["msg"] = "<strong>No session!</strong>";
} else {
//get the userinput from the session
$userinput = $this->session->userdata('studentNationalId');
$data["msg"] = "ID:". $userinput;
}
$this->load->view("view_addhist_scholarshipdetails",$data);
}
View: Stage 1 - "view_addhist_selectstudent.php"
<?php $formAttributes = array('role' => 'form', 'style' => 'width: 600px;'); ?>
<?php echo form_open('scholarshiphistory/addhist_scholarshipdetails', $formAttributes); ?>
<div class="form-group">
<div class="panel panel-default">
<div class="panel-body">
<div class="form-group">
<label for="studentSearch">Student:</label>
<input type="text" name="studentSearch" class="form-control" id="studentSearchInput" placeholder="student num" value="">
<br>
<span id="searchResult" class="help-block" ></span>
<button id="studentSearchBtn" class="btn btn-default">Search</button><!--search button returns info on user input in span above-->
</div>
</div>
</div>
<button id="studentSubmitBtn" type="submit" class="btn btn-default" >Next</button> <!--this is the submit button-->
</div>
</form>
View: Stage 2 - "view_addhist_scholarshipdetails"
<?php echo $msg; ?>
When I run the code I get to the view 'view_addhist_scholarshipdetails' and it shows the first branch of the if statement in the function addhist_scholarshipdetails in the controller, i.e "no session".
I moved the code to set the session from the first method in the controller to the second method (also in the controller) and it works okay now, i.e. the session is getting set with the set_userdata method!
Second method now looks like this:
//stage 2 of multipart form
public function addhist_scholarshipdetails(){
if($this->input->post('studentSearch')){
$this->session->set_userdata('studentNationalId', $this->input->post('studentSearch'));
}
if (!$this->session->userdata('studentNationalId')) {
//no session
$data["msg"] = "<strong>No session!</strong>";
} else {
//get the userinput from the session
$userinput = $this->session->userdata('studentNationalId');
$data["msg"] = "ID:". $userinput;
}
$this->load->view("view_addhist_scholarshipdetails",$data);
}
The method I was trying previously seemed to work okay for this guy: http://runnable.com/UhIVTnEfFJEMAAB5
But I think it was because he wasn't setting his session in the same way I was.
Thank so much to those guys who responded to the question.

Codeigniter form on same page as results

I am using codeigniter and the tutorial from here. I have made a basic blog tool which works fine. However as it stands to add a new post you have to go to a separate page 'create.php' to get to the form. I would like to try and put the form on the same page as the page that will be updated i.e. 'index.php'. If I try to do this at the moment the form simply refreshes and does submit the data.
model
function insert_post($data){
$this->db->insert('posts', $data);
return;
}
Current View (admin/create.php)
<?php echo validation_errors(); ?>
<h4>Create A New Post Below</h4>
<form action="" method="post" >
<p>Title:</p>
<input type="text" name="title" size="50"/><br/>
<p>Summary:</p>
<textarea name="summary" rows="2" cols="50"></textarea><br/>
<p>Post Content:</p>
<textarea name="content" rows="6" cols="50"></textarea><br/>
<input type="submit" value="Save" />
<?php echo anchor('admin','Cancel'); ?>
</form>
View I would like the form to be on (index.php)
<?php
echo '<p>Welcome '.$username.'! All posts available for edit or deletion is listed below.</p><br/>';
echo anchor('admin/create','Create New Post');
$count = count($post['id']);
for ($i=0;$i<$count;$i++)
{
echo '<div class="postDiv">';
echo '<h4>'.$post['title'][$i];
echo '<p>'.$post['summary'][$i].'</p>';
echo '<p>'.$post['content'][$i].'</p>';
//echo anchor('blog/view/'.$post['id'][$i],' [view]');
echo anchor('admin/edit/'.$post['id'][$i],' [edit]');
echo anchor('admin/delete/'.$post['id'][$i],' [delete]</h4>');
echo '</div>';
}
?>
Controller
function create(){
$data['userId'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('summary','summary','required');
$this->form_validation->set_rules('content','content','required');
if($this->form_validation->run()==FALSE)
{
$this->load->view('template/admin_html_head',$data);
$this->load->view('admin/create',$data);
$this->load->view('template/html_tail',$data);
} else {
$data = $_POST;
$this->posts->insert_post($data);
redirect('admin');
}
}
This was straight forward when I used normal php but with codeigniter I am getting lost with the MVC stuff. I know this is probably a fairly basic question so please either explain your answer or give me a link to something which will explain what I need to do as I want to learn from this. I have read the codeigniter docs on validation but I dont think thats my problem?
What you are trying to do is called embedding a view. I will try to explain how but you should also check some links which might prove to be more in depth:
http://net.tutsplus.com/tutorials/php/an-introduction-to-views-templating-in-codeigniter/
Codeigniter: Best way to structure partial views
The crux of what you need to do is change the link on index.php from:
echo anchor('admin/create','Create New Post');
to
$this->load->view('admin/create');
Now this should work, but to help you on the MVC front, it helps to explain why doing it this way is wrong. The idea of MVC is to seperate the functions in your application into their distinct roles. Most people will frown at putting business logic into views unless it is very minimal. The way that we could improve upon your code is to load the view in the controller, and set it to variable.
At the bottom of the codeigniter docs for views it shows how to load into a variable:
http://ellislab.com/codeigniter/user-guide/general/views.html
if the third parameter of load->view is set to true then the function will return your view as a string instead of outputting it to the browser
$data['input_form'] = $this->load->view('admin/create', $data, true);
then in the view that you want to load that form all you need to do is echo input_form
<?php echo $input_form;?>
So that should solve your problem but there are also a few more things you can do in your view file that will improve the readability of your code.
Instead of using a count() and for loop you can use foreach which makes everything much easier
<?php foreach ($post as $post_item):?>
<div>
<h4><?php echo $post_item['title'];?></h4>
</div>
<?php endforeach;?>
It also helps to break your view files up and have more tags. It might seems like it is extra bloat, but when you have larger view files it will be very cumbersome to continue using as many echo's as you have
just add one method uri_string() in your form action, uri_string will take same url of page put in action you can submit form to same page
<?php echo validation_errors(); ?>
<h4>Create A New Post Below</h4>
<form action="<?=uri_string()?>" method="post" >
<p>Title:</p>
<input type="text" name="title" size="50"/><br/>
<p>Summary:</p>
<textarea name="summary" rows="2" cols="50"></textarea><br/>
<p>Post Content:</p>
<textarea name="content" rows="6" cols="50"></textarea><br/>
<input type="submit" value="Save" />
<?php echo anchor('admin','Cancel'); ?>
</form>
in controller little chagnes
function create(){
$data['userId'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('summary','summary','required');
$this->form_validation->set_rules('content','content','required');
if($this->form_validation->run()==FALSE)
{
$this->load->view('template/admin_html_head',$data);
$this->load->view('admin/create',$data);
$this->load->view('template/html_tail',$data);
} else {
$data = $this->input->post();
$this->posts->insert_post($data);
redirect('admin');
}
}
Use session library
check this another stackoverflow thread to know how to use session
In order to use session library, u need to configure encryption_key in config.php
To do that, check this out

Symfony form->bind fails

I'm working with a few custom forms, and one of them isn't binding it's values on a POST. I'm using the same logic for each, and only one of them isn't working. Here's the code:
public function executeMediaFileUpload(sfWebRequest $request) {
$this->form = new MediaFileUploadForm();
if (!$request->isMethod('POST'))
$psk = $request->getParameter('psk');
else {
$this->form->bind($request->getParameter($this->form->getName()), $request->getFiles($this->form->getName()));
$this->logMessage('VALUE: ' . $this->form->getValue('version'));
$psk = $this->form->getValue('application');
}
$this->logMessage('PSK: ' . $psk);
$app = Doctrine::getTable('Application')->find(array($psk));
$this->form->setDefault('application', $app->getPsk());
$this->form->setDefault('version', $app->getVersion()->getLast()->getPsk());
On the initial GET, I can see the value passed in via psk getting set as the default for application in the generated HTML, and all the values show up in the POST request in Firebug, but after I bind the form, it still contains no values.
EDIT:
Yes, the form is setup as multipart and POST. And I'm calling $this->widgetSchema->setNameFormat('values[%s]') in the form.
EDIT2: Here's the HTML for the form, and getName returns "values":
<form name="mediafiles" action="<?php echo url_for('application/mediaFileUpload') ?>" method="POST" <?php $form->isMultipart() and print 'enctype="multipart/form-data" ' ?> id="applications">
<div class="clear">
<div>
<?php echo $form->renderHiddenFields() ?>
<?php foreach($form as $widget): ?>
<?php if (!$widget->isHidden()): ?>
<?php echo $widget->renderLabel() ?>
<?php echo $widget->renderError() ?>
<?php echo $widget->render() ?>
<?php endif ?>
<?php endforeach ?>
</div>
</div>
<!-- Start Bottom Sub Navigation -->
<div class="subnav clear">
Cancel
Upload
</div>
<!-- End Bottom Sub Navigation -->
Check in the code generated on your browser (or firebug) for the form. Form values use to have a name, according to your "name format" configuration, like this:
<input type="text" name="my_name_format[widget_name]" />
So in order to access its value passed to action you must use something like this:
$parameters = $request->getParameter('my_name_format');
$parameter = $parameters['widget_name'];
And like this for each value of your form using "parameters" array.
An simple draft implementing my solution into your code looks like this:
public function executeMediaFileUpload(sfWebRequest $request) {
$this->form = new MediaFileUploadForm();
$parameters = $request->getParameter('values'); // Since you used $this->widgetSchema->setNameFormat('values[%s]')
if (!$request->isMethod('POST'))
$psk = $parameters['psk'];
else {
$this->form->bind($request->getParameter($this->form->getName()), $request->getFiles($this->form->getName()));
$this->logMessage('VALUE: ' . $parameters['version']);
$psk = $parameters['application'];
}
$this->logMessage('PSK: ' . $psk);
$app = Doctrine::getTable('Application')->find(array($psk));
$this->form->setDefault('application', $app->getPsk());
$this->form->setDefault('version', $app->getVersion()->getLast()->getPsk());
Hope this solution works.

Categories