Restrict textarea to a certain number of characters

Hi,

I have a textarea field, which I want to limit to 250 characters. I found a nice jQuery plugin for this:

http://www.tomdeater.com/jquery/character_counter/

and (being a yii newbie) I wonder what would be the right way to use it. I could set and “id” for textarea and then hook it up to jQuery. However, I don’t know how to include this jQuery plugin and where to place the “hook” code.

I assume I could put the jquery.charcounter.js in “assets” directory, but I don’t know how to tell Yii to load it. I could place <script> tag in view manually, but something tells me there’s a “yii-way” to do it.

The other thing I don’t know is where to place jQuery code, you know, the document-ready and all the stuff inside. I could do it in view file, but somehow I feel there’s more to it with Yii. Of course, the coolest thing would be just to be able to say “create a textarea with 250 character limit imposed by jQuery” but I don’t see anything like that in Yii? Is there maybe some extension that does this already?

register your jquery


Yii::app()->clientScript->registerCoreScript('jquery');

since your jquery.charcounter.js is dependent on it.

Then register your jquery.charcounter.js


Yii::app()->clientScript->registerScriptFile('location to your js script');

eg:


Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl.'/assets/js/jquery.charcounter.js');

then register your hook


Yii::app()->clientScript->registerScript('limitText','$("#textAreaId").charCounter(1000);');

take a look at framework/web/ClientScript.php for more information. Play around with the different methods of doing things. To do things more manually, you may use methods from CHtml helper.

Thanks.

Where do I put this code to register stuff? In controller, view or …?

Somehow I feel I should not bloat the view with it, but OTOH view is not really functional without it.

And another question: where do I copy the jquery.charcounter.js file, in yii/framework/web/js/source or should I create a "js" directory under assets?

I’m trying to discover why are those directories with funny names generated under “assets”, and whether I need to use that mechanism for scripts that I add.

Thank you again for your quick replies.

you can put it in your controller or layout/views. You should put it where it best works for your application. (I would recommend putting it in your layout/views). you can put your js file wherever is accessible through your web browser. for organizational purposes i create a folder under assets called js. It’s not recommended that you add to core directories or modify the core unless you really need to. The name of the directory of scripts for core js functionality is produced by this method from CAssetManager


	protected function hash($path)

	{

		return sprintf('%x',crc32($path.Yii::getVersion()));

	}

. You do not need to use that mechanism for scripts that you add. you can look into framework/web/CAssetManager for some info.

It’s not recommended to manually put files in assets directory.

Better put in in your protected folder (eg protected/js/jquery.charcounter.js)

and publish it




<?php

$scriptFile = Yii::app()->assetManager->publish(path/to/script);

Yii::app()->clientScript->registerScriptFile($scriptFile);

?>



Guys, you are giving me contradictory advises. Why is it not recommended to put manually in assets? I’d like to learn what’s the benefit of publishing?

Also, placing in "protected/js" means I have to create "js" there. If I decide to do that, what is the "path/to/script"? Is it "protected/js/jquery.charcounter.js". One thing I find lacking in Yii documentation is lack of preciseness. In many functions, argument is $path, without saying what is this path relative to, web url, application url, yii folder url? Should one use absolute or relative path?

Is there really no convention or best-practice here? I fear what will happen if more developers join me and start adding stuff all around the place. Does this mean my development team needs to setup some conventions first, before using Yii as a framework?

P.S. Spyros, some of the issues I raised are obviously not your fault, but I hope some of Yii developers are reading this forum.

If you put your javascripts in protected/js then path to folder is

Yii::app()->getBasePath().DIRECTORY_SEPARATOR."js"

Yii::app()->getBasePath() is pointing to the protected directory

The assets directory is used for publishing private files so they become accessible to the web clients

If you don’t want your scripts to be protected you can put them in a dir like webroot/js

The one reason I can think of to not use a subfolder to assets for your public scripts is that you’ll frequently want to delete all published subfolders.

A benefit of publishing is to make protected content e.g in widgets, modules and the framework itself, available to web users.

/Tommy

Thanks. That makes perfect sense for PHP code.

But, I fail to see the benefit of keeping javascript source protected when client will see the path to it anyway?

Some framework components require images and CSS/JS files to be publicly accessible. Since the framework code is not accessible from web (and doesn’t even have to be located in your webfolder), these files need to be “published” before. That’s what the assets folder is for. But it is solely managed by CAssetManager. You shouldn’t put files manually in there. And you can even delete it’s content - it will be automatically regenerated.

Same is of course true for your own components. You might want to reuse them in different applications and keep their code + images + js + css on one place. So you can publish the required assets from your component code and users will be able to "see" them.

That explains all. Thanks.

Hey guys, know the post is a bit old but I need hel p implementing this lol. Im a complete noob when it comes to this, id never even looked at php till a week ago and im trying to learn how to use that and Yii together.

So I have my page and it looks a bit like this.




<?php

Yii::app()->clientScript->registerCoreScript('jquery');

Yii::app()->getClientScript()->registerScriptFile(Yii::app()->baseUrl . '/js/jquery-1.4.4.js');

Yii::app()->getClientScript()->registerScriptFile(Yii::app()->baseUrl . '/js/jquery.charcounter.js');

Yii::app()->clientScript->registerScript('limitText','$("#RejectReason").charCounter(5);');

$this->pageTitle = Yii::app()->name . ' - Reject Offer';

$this->breadcrumbs = array(

    'Review Offer', 'Reject Offer',

);

?>

<?php echo CHtml::form('', 'post'); ?>


<?php

$form = $this->beginWidget('CActiveForm', array(

            'id' => 'editOffer-form',

            'enableAjaxValidation' => true,

        ));

?>


<p>Please enter a reason for your rejection of the offer</p>

<div class="form">

    <table width ="100">

        <tr>

            <?php

            echo $form->textArea($model, 'RejectReason', array('rows' => 5, 'cols' => 50));

            ?>

        </tr>

        <br>

        <tr>

            <td align ="left" width="50">

        <input type="submit" name="Reject" value="Reject"

               class="buttonAsLink"

               onmouseover="this.className='buttonAsLink_hover';"

               onmouseout="this.className='buttonAsLink';" /></td>


            <td align ="right" width="50">

        <input type="submit" name="Cancel" value="Cancel"

               class="buttonAsLink"

               onmouseover="this.className='buttonAsLink_hover';"

               onmouseout="this.className='buttonAsLink';"/></td>

        </tr>




    </table>

</div>

<?php $this->endWidget(); ?>

<script type='text/javascript'>


   $(document).ready(function() {

$("#RejectReason").charCounter();

});




</script>

My question is how do I get this to work, im trying to limit the textarea to 5 characters as a test yet it wont work with what I have above. Any help would be greatly appreciated,my next step is to bang my head off a wall ha!. Cheers

Any help is appreciated, thanks :)

Try this




Yii::app()->clientScript->registerScript('limitText',

  '$("#'.CHtml::activeId($model, 'RejectReason').'").charCounter(5);');



/Tommy

Hi Tommy,

Thanks for the reply however im afraid that has not worked :(.

I forgot to escape quotes, try again




Yii::app()->clientScript->registerScript('limitText',

  '$("#'.CHtml::activeId($model, \'RejectReason\').'").charCounter(5);');



/Tommy

Cheers again Tommy but I seem to be getting an error, im sure its something to do with the syntax however for the life of me I cant seem to find it, I keep getting Unexpected String error. Maybe I need a new set of eyes or a lot of coffee haha.

Argh nevermind I found the error, was just a simple mistake lol, sorry about that however it still doesnt limit the characters.

It turns out quoting shouldn’t be escaped, what I suggested actually generates an error.

Which char counter do you use? I googled and found this:

http://tomdeater.com/jquery/character_counter/

Here’s one from the jQuery site you my want to try

http://plugins.jquery.com/plugin-tags/char-counter

/Tommy

Im using the First one u linked, the http://tomdeater.com/jquery/character_counter/ one. I shall indeed try out the other one tommorrow :). Cheers for all the help dude.