In Zend Framework I'm trying to display an image through my controller.
class PictController extends Zend_Controller_Action
{
public function indexAction()
{
$objpict = new Application_Model_Page();
$objpict->CheminPictures(Application_Model_String::ExtractNamePict($this->getParam('niveau0')));
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->getHelper('layout')->disableLayout();
header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($file));
echo file_get_contents($file);
exit;
}
}
A road was also created, but it is not taken into account either!
$routeRegex = new Zend_Controller_Router_Route_Regex(
'img/([a-z-0-9-/-]+).jpg',
array('controller' =>'pict','action' => 'index'),
array(1 => 'niveau0',2 => 'niveau1',3 => 'niveau2'),'img/%s.jpg');
$this->_routeur->addRoute('routeimage', $routeRegex);
This does not work. It returns me the url of my page ...
<img alt="montitre" src="<?php echo $this->url(array('controller' => 'pict', 'action' => 'index')); ?>" >
How to call the controller from my sight so that it returns me the information?
Thank'you very much !
++
ps: sorry for English
Related
In my Yii application, Yii's default Ajax is not working. Also default Ajax validation is not working. Has this been an installation problem or any other problem. How to enable Yii's default Ajax.
In my controller,
public function actionCreate() {
$model = new Company;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if (isset($_POST['Company'])) {
$company = Company::model()->findAll();
if (count($company) === 0) {
$model->attributes = $_POST['Company'];
$uploadedFile = CUploadedFile::getInstance($model, 'logo');
if (isset($uploadedFile)) {
$fileName = date('Ymdhis') . '_' . $uploadedFile->name; // $timestamp + file name
$model->logo = $fileName;
}
if ($model->validate()) {
if ($model->save()) {
if (isset($uploadedFile)) {
$uploadedFile->saveAs(Yii::app()->basePath . '/../banner/' . $fileName);
}
$this->redirect(array('create'));
}
}
} else {
Yii::app()->user->setFlash('error', 'Company details is already exists.');
}
}
$this->render('create', array(
'model' => $model,
));
}
In view page,
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'company-form',
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnChange' => true,
'validateOnSubmit' => true,
),
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation' => true,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
<div class="form-group">
<?php echo $form->label($model, 'company_name', array('class' => 'req')); ?>
<?php echo $form->textField($model, 'company_name', array('class' => 'form-control')); ?>
<?php echo $form->error($model, 'company_name', array('class' => 'school_val_error')); ?>
</div>
Please help me.
Thanks...
Yii has no default AJAX. This is a technology based on JavaScript language. By default Yii includes a jQuery library which provided some methods for easy manipulations with AJAX. If you want use it on your page, you should add this string:
Yii::app()->clientScript->registerCoreScript('jquery');
You can add this string to your main layout, for example into top of /views/layouts/main.php`
I have a ajax link in yii when user click it do something and update a element html (content of td) without refresh page how can change 2 element html?
I explain more:
in view i have a table by some td for show information a td for send information (there are a image ajaxlink) and a td by message of content (example: "not send")
When user click image link call a function and valid information (...) and change message of td ('validation is success').("not send" change to "validation is success")
I did what I was told but i want to remove ajaxlink and replace it by a simple image how
can I do it?
i add:
CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/email-send.png", '', array('title' => 'sended success'))
view.php:
<td id="send_<?php echo CHtml::encode($profileInformationServices->id); ?>"><?php echo "not send"; ?></td>
<td id="sended_<?php echo CHtml::encode($profileInformationServices->id); ?>">
<?php
echo $profileInformationServices->send ? CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/email-send.png", '', array( 'title' => 'sended success')):
CHtml::ajaxLink(CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/send.png", '', array(
'title' => 'Send for valid')), Yii::app()->createUrl('/profileInformationService/send'),
array( // ajaxOptions
'type' => 'POST',
'data' => array( 'id' => $profileInformationServices->id ),
'update' => '#send_'.$profileInformationServices->id,
)
);
?>
</td>
controller:
public function actionSend() {
if (Yii::app()->request->isPostRequest) {
$model = $this->loadModel($_POST["id"]);
$model->send = 1;
$model->save();
echo "sended success";
}
}
Use ajaxLink callback to change the text in td.
<?php
//I am keeping your ternary code in if-else condition for readability
if($profileInformationServices->send)
{
echo CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/email-send.png", '', array('title' => 'sended success'));
}
else
{
echo CHtml::ajaxLink
(
CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/send.png", '', array('title' => 'Send for valid')),
Yii::app()->createUrl('/profileInformationService/send'),
array
(
'type' => 'POST',
'data' => array('id' => $profileInformationServices->id),
'success'=>'function(data)
{
if(data=="sended success")
{
$("#send_'.$profileInformationServices->id.'").html("validation is success");
}
}',
)
);
}
?>
I'm tring to validate a login form and sending error messages using flashdata. Flashdata seems to have a delay, it's only affected a second submit (no error message is shown after first submit, ok after second), whereas userdata works correctly.
View>
<?php if ($this->session->flashdata('error_messages')): ?>
<?php echo $this->session->flashdata('error_messages'); ?>
<?php endif; ?>
<?php echo form_open('user/login', array('name' => 'login_form', 'id' => 'login_form')); ?>
<fieldset>
<p>
<?php echo form_label('Username: ', 'username'); ?>
<?php echo form_input('username', set_value('username', ''), array('id' => 'username', 'placeholder' => 'username')); ?>
</p>
<p>
<?php echo form_label('Password: ', 'password'); ?>
<?php echo form_password('password', set_value('password', ''), array('id' => 'password', 'placeholder' => '********')); ?>
</p>
<p>
<?php echo form_submit('login', 'Login', array('id' => 'login')); ?>
</p>
Controller action>
public function login() {
//user is not logged in, carry on
if (!user_is_logged_in()) {
//check if form was already submitted, if yes validate
if ($this->input->post('login')) {
$this->load->library('chronos_user');
//gather data from form
$username = $this->input->post('username');
$password = $this->input->post('password');
//validate form, show error messages if not valid
if (
!($this->chronos_user->valid_username($username)) ||
!($this->chronos_user->unique_username($username))
)
{
$this->chronos_template->set_data('header', array('controller' => 'users', 'action' => 'login', 'title' => 'Login'));
$this->chronos_template->set_view('content', 'user/login_view');
$this->chronos_template->view();
}
//redirect if ok
else {
header("Location http://c4studio.ro");
}
}
//if no form was submitted, just display it
else {
$this->chronos_template->set_data('header', array('controller' => 'users', 'action' => 'login', 'title' => 'Login'));
$this->chronos_template->set_view('content', 'user/login_view');
$this->chronos_template->view();
}
}
//user is already logged in, redirect to profile page
else {
$profile_url = "Location: ";
$profile_url .= site_url();
$profile_url .= "user/profile/";
header($profile_url);
}
}
Valid_username method>
public function valid_username($username) {
if (empty($username)) {
$this->CI->session->set_flashdata('error_messages', 'Value.');
return FALSE;
}
if (strlen($username) < 3) {
$this->CI->session->set_flashdata('error_messages', 'Value11.');
return FALSE;
}
return TRUE;
}
Any ideas? Also if somebody knows a better way to do all this please let me know! Thanks
According to the documentation flashdata exists at the next server request.
But in your case you actually set the flashdata in the same server request as you show the login view which was unsuccesful. Thats the reason it doesn't work.
A better way wuld to just allow your model method to return true or false and use that value instead. The flashdata should only be considered if you redirect the user to an error page or something like that.
As #Repox mentioned, it only works on the 'next refresh'. You are assuming that flashdata works RIGHT AWAY when you set it, but it doesn't you need an new actual page reload / refresh before that is available.
You have the right idea, but you are just using flashdata to implement your message, stick to form messages as a return result, or just a custom variable.
This is really a case of developers designing flashdata for one thing, and users using it for another.
You need to use form_error to return all form errors, don't use flashdata, it will not work as you expect it to.
Examples:
http://codeigniter.com/user_guide/libraries/form_validation.html#settingerrors
You can also override any error message found in the language file.
For example, to change the message for the "required" rule you will do
this:
$this->form_validation->set_message('required', 'Your custom message here');
I'm following the blog tutorial on CakePHP website, but validation doesn't work and I don't understand why, because I'm using the blog tutorial code.
I'll report directly from my files anyway...
MODEL
class Post extends AppModel
{
var $name = 'Post';
var $validate = array(
'title' => array(
'rule' => 'notEmpty'
),
'body' => array(
'rule' => 'notEmpty'
)
);
}
CONTROLLER
class PostsController extends AppController {
var $name = 'Posts';
function index() {
$this->set('posts', $this->Post->find('all'));
}
function view($id) {
$this->Post->id = $id;
$this->set('post', $this->Post->read());
}
function add() {
if (!empty($this->data)) {
if ($this->Post->save($this->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
}
}
}
VIEW (add view)
<h1>Add Post</h1>
<?php
echo $form->create('Post');
echo $form->input('title');
echo $form->input('body', array('rows' => '3'));
echo $form->end('Save Post');
?>
When I reach the /posts/add page and then click to Save without any input text it doesn't reload with error; it inserts the empty data into db and then redirects me with the message "Your post has been saved".
Why doesn't validate itself? I've read into docs that it's not necessary to call validate(); save() is enough.
Any ideas about this?
I found the error: I was naming the model files capitalizing them. So, I had a Post.php instead of a post.php.
CakePHP didn't find my models and so it was using its "generated" models.
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.