PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 27, 2022

[FIXED] Put php code inside of registerScript of yii framework

 February 27, 2022     javascript, php, yii     No comments   

Issue

I want to put a php code inside of Yii::app()->clientScript->registerScript of yii1

How can I put it inside of this one?

<?php Yii::app()->clientScript->registerScript("form", <<<JAVASCRIPT
// I want the PHP code inside of this
JAVASCRIPT, CClientScript::POS_END); ?>

is there a way besides of ending the PHP in the middle of the code?

EDIT

if I put <?PHP ?> in the middle I'm getting an error of

Parse error: syntax error, unexpected end of file in C:\xampp\htdocs\yii\project\protected\views\group_Form.php on line 275

and that line is

JAVASCRIPT, CClientScript::POS_END); ?>

Solution

Since you can access the controller instance via $this in view context, I would suggest you doing something like that:

  1. Create partial view php file where you can build your mixin (js + php) which obviously will contain any script type with some conditions on top of PHP.

  2. Use CBaseController#renderPartial (which actually returns string instead of rendering, according to 3rd parameter return = true) in view context to get the mixin view contents as string and pass it as 2nd parameter to Yii::app()->clientScript->registerScript.

The implementation would look like this:

// _partial_view.php 
// here is your mixin between js + php
/* @var $this CController */

<?php

echo '<script>' .
   Yii::app()->user->isGuest 
   ? 'alert("you\'re guest")' 
   : 'alert("you\'re logged user")' 
. '</script>';

Then go back to your registering js invocation:

<?php Yii::app()->clientScript
                ->registerScript("form",
                                 $this->renderPartial('_partial_view.php', [], true), // setting 3rd parameter to true is crucial in order to capture the string content instead of rendering it into the view
                                 CClientScript::POS_END); ?>


Answered By - G.Spirov
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing